【问题标题】:handle json request in PHP在 PHP 中处理 json 请求
【发布时间】:2011-03-05 01:48:42
【问题描述】:

在进行 ajax 调用时,当 contentType 设置为 application/json 而不是默认的 x-www-form-urlencoded 时,服务器端(在 PHP 中)无法获取 post 参数。
在以下工作示例中,如果我在 ajax 请求中将 contentType 设置为“application/json”,则 PHP $_POST 将为空。为什么会这样?如何在 PHP 中正确处理 contentType 为 application/json 的请求?

$.ajax({
    cache: false,
    type: "POST",
    url: "xxx.php",
    //contentType: "application/json",
    processData: true,
    data: {my_params:123},
    success: function(res) {},
    complete: function(XMLHttpRequest, text_status) {}
});

【问题讨论】:

    标签: php ajax json request mime-types


    【解决方案1】:
    <?php
       var_dump(json_decode(file_get_contents('php://input')));
    ?>
    

    【讨论】:

      【解决方案2】:

      您会在$HTTP_RAW_POST_DATA 中找到无法识别的 MIME 类型。您还可以通过将 php.ini 指令 always_populate_raw_post_data 设置为 true 来强制 PHP 始终填充此数组(不仅适用于无法识别的 MIME 类型)。

      原始帖子数据将通过输入包装器php://input 提供

      更多信息:

      http://us.php.net/manual/en/wrappers.php.php

      http://php.net/manual/en/reserved.variables.httprawpostdata.php

      http://www.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data

      【讨论】:

        【解决方案3】:

        以上在技术上是正确的,但是由于我写的PHP不多,这可能会更有帮助

        xxx.php 是

        <?php
        $file = fopen("test.txt","a");
        $post_json = file_get_contents("php://input");
        $post = json_decode($post_json, true);
        foreach($post as $key=>$value) {
            $message = $key . ":" . $value . "\n";
            echo fwrite($file,$message);
        }
        fclose($file);
        ?>
        

        然后你可以用

        测试
        curl -X POST -H "Content-Type: application/json" -d '{"fieldA":"xyz","fieldN":"xyz"}' http://localhost/xxx.php
        

        【讨论】:

          【解决方案4】:

          如果你有 phalcon 扩展,你可以使用getJsonRawBody ()

          http://docs.phalconphp.com/en/latest/api/Phalcon_Http_Request.html

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-07-06
            • 2012-03-14
            • 1970-01-01
            • 2013-03-18
            • 2011-05-02
            • 1970-01-01
            相关资源
            最近更新 更多