[英]AngularJS not sending data via POST
我正在尝试通过AngularJS $ http.post将某些表单数据保存到JSON,但是不起作用。 这个想法很简单:我有一个包含三个字段的表单,一个AngularJS数据绑定和一个非常简单的PHP代码,将其保存到文件中。 由于PHP文件显然未获得任何输入,因此它不起作用,因此它始终存储null
。
这是代码:
HTML表单:
<form class="form-horizontal">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title:</label>
<div class="col-md-4">
<input type="text" class="form-control" id="title" ng-model="book.title" placeholder="Title">
</div>
</div>
<div class="form-group">
<label for="pages" class="col-sm-2 control-label">Pages:</label>
<div class="col-md-1">
<input type="number" class="form-control input-sm" id="pages" ng-model="book.pages" placeholder="0">
</div>
</div>
<div class="form-group">
<label for="readPages" class="col-sm-2 control-label">Read pages:</label>
<div class="col-md-1">
<input type="number" class="form-control input-sm" id="readPages" ng-model="book.readPages" placeholder="0">
</div>
</div>
<button class="btn btn-primary glyphicon glyphicon-floppy-save" ng-click="save()"></button>
</form>
JS代码:
angular.module('book', [
'ui.router'
])
.config(function config($stateProvider) {
$stateProvider.state('book', {
url: '/book',
views: {
"main": {
controller: 'Book',
templateUrl: 'ui/views/book.tpl.html'
},
"header": {
templateUrl: 'ui/views/header.tpl.html'
},
"footer": {
templateUrl: 'ui/views/footer.tpl.html'
}
},
data: {pageTitle: 'Book Status'}
});
})
.controller('Book',
function ($scope, $http) {
$scope.book = {};
$scope.error = "";
$scope.save = function() {
console.log($scope.book);
$http.post('save/book.php', $scope.book).then(function(response) {
// log success
console.log("Guardado con éxito.");
console.log(response);
});
};
});
和PHP代码:
$data = file_get_contents("php://input");
$inp = file_get_contents('../data/books.json');
$tempArray = json_decode($inp);
$tempData = json_decode($data);
array_push($tempArray, $tempData);
$jsonData = json_encode($tempArray);
$file = fopen('../data/books.json','w+');
fwrite($file, $jsonData);
fclose($file);
echo $jsonData;
因此,显然一切都正确,但是我得到了以下响应:
(!)警告:array_push()期望参数1为数组,在第7行的C:\\ wamp \\ www \\ angulardemos \\ save \\ book.php中给出null
这告诉我输入不正确,因此我实际上没有发送任何数据。 我想念什么?
easy $tempArray
为null添加var_dump对其进行调试
$tempArray = $tempArray = json_decode($inp, true);
$tempData = json_decode($data);
array_push($tempArray, $tempData);
您也可以尝试:
$tempArray[]=$tempData;
从ng-model中删除书籍,并将其<input type="text" class="form-control" id="title" ng-model="title" placeholder="Title">
同样适用于所有..,并在保存函数中var dataObj = { title: $scope.title, pages: $scope.pages
}var dataObj = { title: $scope.title, pages: $scope.pages
}var dataObj = { title: $scope.title, pages: $scope.pages
}var res = $http.post('save/book.php', JSON.stringify(dataObj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.