javascript - PHP:响应 AJAX post 请求

标签 javascript php angularjs json ajax

我正在使用 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/

相关文章:

javascript - 关闭 jquery 中的上一个下拉菜单不起作用

javascript - mongoose - 如何从 $pull 中删除元素

javascript - 如何通过 ES6 "class"函数以 Angular 传递数据

html - 如何从 UI-Bootstrap Angular Tab 指令中删除下边距?

javascript - 类型错误 : Cannot assign to read only property - Karma

javascript - 使用带有 NodeJS 的 NightmareJS 进行抓取

javascript - var 不更新,count 不更新

php - 向 Woocommerce 中的总计添加百分比

php - 不同机器上的按位运算结果不同

PHP IMAP 检索 To 地址中的所有收件人