我是Angular JS的新手,我正在尝试使用AngularJs和Json使用javascript制作CRUD表单而不使用任何其他服务器端语言。该脚本工作正常,但无法将数据写入同一目录中同一服务器上的JSON文件。我正在使用xamp。这是代码:
<!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 :(得分: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();
})
答案 1 :(得分:0)
我认为你不能向json文件发布任何内容,因为它只是一个文件而不是服务器上的任何内容(API URL)。