PHP:响应AJAX发布请求

时间:2016-02-10 16:14:31

标签: javascript php angularjs json ajax

我正在使用angular来通过get请求检索json数据。我想通过post更新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);

?>

2 个答案:

答案 0 :(得分:2)

我记得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);

或者您可以配置角度来发送标题,请参阅详细信息here

答案 1 :(得分:0)

使用json_encode函数在json中发送响应

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

你需要在你的PHP脚本中

echo json_encode(['id'=>123]);
相关问题