如何JSON数据发布到一个PHP脚本$ http.post [英] How to post json data to a php script with $http.post
问题描述
我一直有这个问题了一段时间,尝试了多种解决方案,都没有奏效。
我试图用$ http.post到JSON数据发送到一个名为processCustomers.php PHP脚本这是我的API的一部分
I've been having this problem for a while and tried many solutions which haven't worked. I am trying to use $http.post to send json data to a php script named processCustomers.php which is part of my API
POST请求是
angular.extend(obj, {id: id});
$http({
method: 'POST',
url: '../API/processCustomers.php',
headers: { 'Content-Type': 'application/json' },
dataType: 'json',
data: obj
}).success(function (data) {
console.log(data);
});
};
和processCustomers是
and the processCustomers is
$newCustomers = filter_has_var(INPUT_POST, 'newCustomer');
if ($newCustomers) {#request to add new customer
$exceptionalFields = ['customerID']; //
$customersJSON = json_decode(filter_input(INPUT_POST, "newCustomer"));
if (json_last_error() > 0) {
echo DotCom::systemFeedBack("Sorry customer not created unknown error", "data sent is not a json object", 303);
return;
}
foreach ($customersJSON as $key => $customer) {
$parameterTypes = ""; # order determined by the sql returned by validateInputData()
$entries = $func->validateInputData($tableMetaData,$customer, $parameterTypes, $exceptionalFields);
if (!is_array($entries)) {
echo $entries;
return;
}
$results = $customers->createCustomer($entries, $parameterTypes, $link,$status);
当我发送请求,在浏览器控制台说,响应的text / html,而不是应用程序/ json.I经过很多的教程和例子看,我也都试过了folowings:
删除页眉和数据类型 - 不影响
包装在JSON.stringify obj的 - 结果头更改为应用程序/ x-WWW的形式urlen codeD
When I send the request, the console in the browser says the response is text/html instead of application/json.I looked through many tutorials and examples and I also have tried the folowings: removing the headers and datatype - no effect wrapping the obj in JSON.stringify - results in header changing to application/x-www-form-urlencoded
推荐答案
您需要在您的PHP文件如下:
You need the following in your php file:
$json = file_get_contents('php://input');
$obj = json_decode($json);
$ _ POST
将是空当内容类型:应用程序/ JSON
在头传递
据悉几天就回来从这个问题的
这篇关于如何JSON数据发布到一个PHP脚本$ http.post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!