[英]How to read POST Request data in PHP sent from AngularJS
我正在尝试从我的角度js发出发布请求,如下所示
var postData={
firstName:'VenuGopal',
lastName:'Kakkula'
};
postData=JSON.stringify(postData);
$http({method:'POST',url:'http://localhost/blog/posttest.php?insert=true',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function (data,status,headers,config) {
alert('Success' + data);
})
.error(function (data, status,headers,config) {
// uh oh
alert('error' + status + data);
});
我不确定如何在我的PHP REST Web服务中读取此POST数据。
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:Content-Type');
header("Content-Type:application/json");
if(!empty($_GET['insert']))
{
$result=json_decode($_POST['firstName']);
deliver_response(200,"Got the Post data","GotData $result");
}
function deliver_response($status,$statusmsg,$data)
{
header("HTTP/1.1 $status $statusmsg");
$response['status']=$status;
$response['status_message']=$statusmsg;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
我尝试了以下选项
json_decode($_POST['firstName'])
json_decode($_POST['data'])
json_decode($_POST['[postData'])
他们都不返回数据,它总是返回错误未定义的索引:第10行的F:\\ xampp \\ htdocs \\ Blog \\ posttest.php中的firstName
任何人都可以帮助我如何读取php文件中发送的POST请求数据。
这很可能是因为您要提交的JSON数据不是按照标准表单数据自动填充到$ _POST变量中的。
解决方法是将输入手动解析为变量以供使用。
例:
<?php
$args = json_decode(file_get_contents("php://input"));
echo $args->firstName;
?>
您也可以在不更改服务器中代码的情况下解决此问题,并以常规方式使用$_POST
。 在这里解释: http : //victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.