【问题标题】:How to post json data to a php script with $http.post如何使用 $http.post 将 json 数据发布到 php 脚本
【发布时间】:2015-07-25 14:46:32
【问题描述】:

我遇到这个问题已经有一段时间了,并尝试了许多没有奏效的解决方案。 我正在尝试使用 $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);
  });
};

流程客户是

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

【问题讨论】:

  • 有什么问题...用php接收还是用客户端接收?
  • 我对 PHP 了解不多,但您说您的回复是 text\html 类型的,所以您是否尝试在 php 中设置 contenttype,例如 header('Content-Type: application/json');

标签: javascript php json angularjs


【解决方案1】:

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

$json = file_get_contents('php://input');
$obj = json_decode($json);

Content-Type: application/json 传入标头时,$_POST 将为空。

几天前从this问题中了解到

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多