如何使用$ http.post将json数据发布到php脚本

时间:2015-05-14 05:06:27

标签: javascript php json angularjs

我已经有一段时间遇到这个问题并尝试了许多尚未解决的解决方案。 我正在尝试使用$ http.post将json数据发送到名为processCustomers.php的php脚本,该脚本是我的API的一部分

发布请求

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是

$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而不是application / json。我查看了许多教程和示例,我也尝试了以下内容: 删除标头和数据类型 - 没有影响 将obj包装在JSON.stringify中 - 导致标题更改为application / x-www-form-urlencoded

1 个答案:

答案 0 :(得分:1)

您的php文件中需要以下内容:

$json = file_get_contents('php://input');
$obj = json_decode($json);
在标题中传递$_POST时,

Content-Type: application/json将为空。

this个问题

回来几天了解到