2014-12-19 47 views
0

我是Angular JS的新手,並且正在嘗試使用AngularJs和Json使用javascript製作CRUD表單,而不使用任何其他服務器端語言。腳本工作正常,但無法將數據寫入同一目錄中同一服務器上的JSON文件。我正在使用xamp。下面是代碼:使用AngularJs和javascript將數據推送到json文件

<!DOCTYPE html> 
    <html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js">  </script> 
    </head> 

    <body ng-app="myapp"> 
    <div ng-controller="MyController" > 
    <form> 
     <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name <br/> 
     <select ng-model="myForm.car"> 
     <option value="nissan">Nissan</option> 
     <option value="toyota">Toyota</option> 
     <option value="fiat">Fiat</option> 
     </select> 

     <button ng-click="myForm.submitTheForm()">Submit Form</button> 
    </form> 

    <div> 
     {{myForm.name}} 
    </div> 
    <div> 
     {{myForm.car}} 
    </div> 
    </div> 

    <script> 
    angular.module("myapp", []) 
    .controller("MyController", function($scope, $http) { 
     $scope.myForm = {}; 
     $scope.myForm.name = "Jakob Jenkov"; 
     $scope.myForm.car = "nissan"; 
    console.log("Submitting form"); 
    $scope.myForm.submitTheForm = function(item, event) { 
     console.log("Submitting form"); 
     var dataObject = { 
      Name : $scope.myForm.name 
      ,City : $scope.myForm.car 
      ,Country : "India" 
     }; 

     var responsePromise = $http.post("data.json", dataObject); 
     responsePromise.success(function(dataFromServer, status, headers, config) { 
      console.log(dataFromServer.title); 
     }); 
     responsePromise.error(function(data, status, headers, config) { 
      alert("Submitting form failed!"); 
     }); 
    } 

     $http.get('data.json').then(function(data) { 
    console.log(data); 
    }); 

    }); 
</script> 
</body> 

+0

如果沒有像節點或php這樣的服務器端語言,您無法執行CRUD操作。 –

+0

終於找到了答案。將使用PHP作爲此服務器端語言。儘管我們也可以使用其他服務器端語言。 – mikelee

回答

1

你做錯了。爲此,你的後臺應該有一些API。您可以使用expressjs - 這是很簡單的:

app.post('cars/', function(req, res) { 
    writeToFile('data.json', req.body); // I do not know how to write files, something like this 
    res.send(); 
}) 
+0

什麼是'writeToFile('data.json',req.body);' –

0

我不認爲你可以發佈任何的JSON文件,因爲它只是在服務器上的文件,並沒有什麼(API URL)。

相關問題