POST后,json返回null值

时间:2013-07-11 07:35:37

标签: php jquery ajax json null

a.php只会

$(document).ready(function() {
    $("#submit_form").on("click",function(){
        var json_hist =  <?php echo $json_history; ?>;
        $.ajax({
            type: "POST",
            url: "b.php",
            data: "hist_json="+JSON.stringify(json_hist),
            //contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){alert(data);},
            failure: function(errMsg) {
                alert(errMsg);
            }
        });  
    }); 
})

b.php

$obj=json_decode($_POST["hist_json"]);
var_dump($_POST);

如果我评论 contentType: "application/json; charset=utf-8" 一切都运行正常,但如果取消注释。 var转储将返回null。

3 个答案:

答案 0 :(得分:0)

在ajax中设置contentType时,您要为请求设置contentType而不是响应。

它与JSON contentType失败,因为您发送的数据是键/值格式的数据(缺少编码),因此数据与contentType不匹配。 JSON contentType标头适用于您发送没有标识符的原始JSON,但在您的情况下,您有一个标识符hist_json=

我建议改为:

data: { hist_json : JSON.stringify(json_hist) },

使用带有hits_json键的对象意味着jQuery将安全地URL encode JSON,并允许PHP使用$_POST['hits_json']来获取它。


如果要使用JSON contentType,则必须将ajax更改为:

data: { JSON.stringify(json_hist) }, // <-- no identifier

和PHP:

$obj = json_decode($HTTP_RAW_POST_DATA);
var_dump($obj);

答案 1 :(得分:0)

据我所知,这是FireFox中出现的错误。

您可以在http://bugs.jquery.com/ticket/13758

上阅读更多内容

stackoverflow中还有关于它的主题

Cannot set content-type to 'application/json' in jQuery.ajax

答案 2 :(得分:0)

您注释掉的行正在尝试将Content-type:标题更改为application/json。虽然您发送的数据是JSON格式,但数据是作为HTTP POST请求传输的,因此您需要使用application/x-www-form-urlencoded;的内容类型,这是默认值。这就是为什么它适用于删除的行。

相关问题