我试图将数组保存到位于网络服务器上的JSON文件中。 响应是成功的,但是当我打开JSON时,它完全是空的。
我尝试手动创建自己的JSON对象,但结果相同。
以下是这个过程:
app.controller('BookController', ['$window', '$http', function ($window, $http) {
this.contacts = [];
this.exportContacts = function(contacts){
$http({
method: "POST",
url: '/data/contacts.json',
headers: { 'Content-Type': 'application/json' },
data: contacts
}).then(function goodCall(){
$window.alert("Save done!");
}, function badCall(){
$window.alert("Failed to save error! error: " + $http.status);
});
};
}]);

我通过表单填充数组:
<form name="addCont" ng-show="showForm" ng-controller="ContactController as contactCtrl" ng-submit="contactCtrl.addContact(addCont, bookCtrl.contacts)" novalidate>
<label>
First Name:
<input name="fname" type="text" required ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.firstName"></input>
<span style="color:red" ng-show="addCont.fname.$dirty && addCont.fname.$invalid">
<span ng-show="addCont.fname.$error.required">First Name is required.</span>
<span ng-show="addCont.fname.$error.pattern">First name must contain letters only!</span>
</span>
</label>
<label>
Last Name:
<input name="lname" type="text" ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.lastName"></input>
<span style="color:red" ng-show="addCont.lname.$dirty && addCont.lname.$invalid">
<span ng-show="addCont.lname.$error.pattern">Last name must contain letters only!</span>
</span>
</label>
<label>
Phone Number:
<input name="phone" type="tel" required ng-model="contactCtrl.contact.phone" ng-minlength="9" ng-maxlength="10" ng-pattern="/^(\d)+$/"></input>
<span style="color:red" ng-show="addCont.phone.$dirty && addCont.phone.$invalid">
<span ng-show="addCont.phone.$error.minlength">Phone number is too short!</span>
<span ng-show="addCont.phone.$error.maxlength">Phone number is too long!</span>
<span ng-show="addCont.phone.$error.required">Phone number is required!</span>
<span ng-show="addCont.phone.$error.pattern">Must not contain letters!</span>
</span>
</label>
<label>
Notes:
<input name="notes" type="text" ng-model="contactCtrl.contact.notes"></input>
</label>
<input type="submit" value="Submit" ng-disabled="addCont.fname.$invalid || addCont.lname.$invalid || addCont.phone.$invalid" />
</form>
&#13;
所以数组应该看起来像这样:
[{
firstName: "Tim",
lastName: "asdxc",
notes: "asdasd",
phone: "0532753940"
},{
firstName: "Timz",
lastName: "asdasd",
notes: "asdasd",
phone: "123123123"
}]
在发送数据之前,我是否需要解析数组?
答案 0 :(得分:0)
答案 1 :(得分:0)
您为$ http提供的网址应该是一项网络服务。 它不适用于文件。
你必须创建一个在服务器端创建文件的web服务(php / node.js / java ...)并从$ http
调用它答案 2 :(得分:0)
我认为网址属性必须是&#39; api / contacts&#39;: 鉴于您必须拥有Web服务或Web api控制器:ContactsController
$http({
method: "POST",
url: 'api/contacts',
headers: { 'Content-Type': 'application/json' },
data: contacts
}).then(function goodCall(){
$window.alert("Save done!");
}, function badCall(){
$window.alert("Failed to save error! error: " + $http.status);
});