PHP:响应 AJAX 发布请求


PHP: respond to AJAX post request

我正在使用角度通过get请求检索json数据。我想通过发布类似地更新 json 文件,并通过发回更新的 json 让 PHP 做出响应。问题是更新 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 标头,因此在 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 以发送标头,请参阅此处的详细信息。

使用json_encode函数以 JSON 格式发送响应

检查 http://php.net/manual/en/function.json-encode.php

在你的PHP脚本中,你需要做

echo json_encode(['id'=>123]);