我正在使用angular通過獲取請求來檢索json數據。我想通過發佈類似的方式更新json文件,並通過發送更新的json來響應PHP。問題是,當json文件更新時,頁面沒有更新(ajax)。PHP:迴應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);
?>
你在PHP中使用什麼樣的堆棧?傳統的PHP?框架?等等... – Okazari
@Okazari我正在使用mamp。 – Almac
@Almac關於你的問題,沒有任何東西從服務器返回 - 你實際發佈到像「https://api.myjson.com/bins/16mjh」這樣的URL嗎?您是否忘記將這些URL更改爲本地服務器URL? –