我正在使用jQuery将json对象发布到我的php应用程序中。
jQuery.post("save.php",JSON.stringify(dataToSend), function(data){ alert(data); });
从firebug中提取的json字符串如下所示
{ "data" : [ { "contents" : "This is some content",
"selector" : "DIV.subhead"
},
{ "contents" : "some other content",
"selector" : "LI:nth-child(1) A"
}
],
"page" : "about_us.php"
}
在php中,我试图将其转换为一个关联数组。
到目前为止我的php代码是
<?php
$value = json_decode(stripcslashes($_POST));
echo $value['page'];
?>
对ajax调用的响应应该是"about_us.php“,但返回为空。
发布于 2011-04-27 23:56:45
如果请求正文不是标准的form编码形式,则不会填充$_POST
。
取而代之的是,像这样从read-only php://input
stream中读取以获得原始请求正文:
$value = json_decode(file_get_contents('php://input'));
发布于 2011-04-27 23:59:19
如果需要关联数组,则将第二个参数作为true传递,否则将继续返回object。
$value = json_decode(stripslashes($_POST),true);
发布于 2011-04-27 23:58:31
尝试:
echo $value->page;
因为json_decode
的默认行为是返回stdClass
类型的对象。
或者,将第二个可选的$assoc
参数设置为true
$value = json_decode(stripslashes($_POST), true);
echo $value['page'];
https://stackoverflow.com/questions/5806971
复制相似问题