我正在使用 Angular 通过 get 请求检索 json 数据。我想通过类似的方式更新 json 文件,并让 PHP 通过发回更新后的 json 进行响应。问题是当 json 文件更新时,页面没有更新(ajax)。
HTML
<html ng-app="myApp">
<body ng-controller="mainController">
<div>
<h3>Rules</h3>
<ul>
<li ng-repeat="rule in rules">{{rule.rulename}}</li>
</ul>
</div>
<div>
<label>New Rules:</label>
<input type="text" ng-model="newRule" />
<input type="button" ng-click="addRule()" value="Add" />
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope','$http', function($scope, $scope.getItems = function() {
$http.get("localhost:8888/json/newRules.json")
.then(
function(response){
//success callback
$scope.rules = response.data;
},
function(response){
// failure callback
console.log(response);
}
);
};
$scope.getItems();
$scope.newRule = '';
$scope.addRule = function() {
$http.post("localhost:8888/json/newRules.json", JSON.stringify([{rulename: $scope.newRule}]))
.then(
function(response){
//success callback
$scope.getItems();
$scope.rules = response;
$scope.newRule = '';
},
function(response){
// failure callback
console.log(response);
}
);
};
}]);
PHP
<?php
$data = file_get_contents("newRules.json");
$data2 = file_get_contents("php://input");
$postData = json_decode($data);
$postData2 = json_decode($data2);
$newArray = array_merge($postData, $postData2);
$newPost = json_encode($newArray);
file_put_contents("newRules.json", $newPost);
?>
最佳答案
我记得 Angular 不会自动向请求添加 application/x-www-form-urlencoded
header ,因此在 php 端,您可能还需要以这种方式解码 POST 数据:
// get the POST data
$data = file_get_contents("php://input");
$postData = json_decode($data);
// process the data
// ...
// send response
echo json_encode($responseData);
或者你可以配置 Angular 发送 header,详情见here .
关于javascript - PHP:响应 AJAX post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35320319/