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]);
相关文章:
- ajax请求的顺序总是不同的
- Meteor如何接收HTTP请求
- 有没有一种方法可以防止img get请求使用css或js发生
- 获取ajax请求的请求头
- NodeJS中POST请求的请求体为null
- Acync JS HTTP请求通知请求
- 将数据存储在请求与请求中
- Ajax”;链接_;当点击非常快时发送多个请求控制器请求(Rails4)
- 从请求.js请求方法返回结果
- 如何发出许多 Node.js 请求(使用请求模块)
- AJAX 请求收到“请求的资源上不存在'访问控制-允许源'标头”错误
- SCRIPT5022:集合尚未初始化.尚未请求或请求尚未执行
- Google Maps REST API - AJAX 请求的请求限制
- 正在获取具有延迟对象的异步请求的请求参数
- ajax请求时请求方法的奇怪行为
- 如何向asp.net MVC 4控制器发送ajax请求以请求XML响应
- 如何从ajax post请求的请求字符串中获取参数
- 事件,然后再发送Ajax请求(向请求添加一些数据)
- 使用iMACROS在运行Javascript后监控/记录HTTP请求(图像请求)
- 错误请求后请求在spring-boot和angularjs之间出现错误