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。
当您在ajax中设置contentType时,您为请求而不是响应设置contentType。
JSON contentType失败,因为您发送的数据是键/值格式的数据(缺少编码),因此数据与contentType不匹配。JSON contentType头用于发送没有标识符的原始JSON,但在您的情况下,您有一个标识符hist_json=
。
我建议改为:
data: { hist_json : JSON.stringify(json_hist) },
使用带有hits_json
键的对象将意味着jQuery将安全地对JSON进行URL编码,并允许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);
据我所知,FireFox中出现了一个bug。
你可以在上阅读更多http://bugs.jquery.com/ticket/13758
stackoverflow中也有关于它的主题
无法将内容类型设置为';application/json';在jQuery.ajax 中
您注释掉的行正试图将Content-type:
标头更改为application/json
。虽然您发送的数据是JSON格式的,但数据是以HTTPPOST请求的形式传输的,因此您需要使用默认的application/x-www-form-urlencoded;
内容类型。这就是为什么它可以在删除线路的情况下工作。