从 $_POST 中的 json 读取关联数组
我正在使用 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”,但它返回空白。
I am using jQuery to post a json object to my php application.
jQuery.post("save.php",JSON.stringify(dataToSend), function(data){ alert(data); });
The json string as pulled from firebug looks like this
{ "data" : [ { "contents" : "This is some content",
"selector" : "DIV.subhead"
},
{ "contents" : "some other content",
"selector" : "LI:nth-child(1) A"
}
],
"page" : "about_us.php"
}
In php I am trying to turn this into an associative array.
My php code so far is
<?php
$value = json_decode(stripcslashes($_POST));
echo $value['page'];
?>
The response to the ajax call should be "about_us.php" but it comes back blank.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果请求正文不是标准 urlencoded 形式,则不会填充
$_POST
。相反,从 只读
php://input
流读取 像这样获取原始请求正文:$_POST
will not be populated if the request body is not in the standard urlencoded form.Instead, read from the read-only
php://input
stream like this to get the raw request body:您可以避免使用
JSON.stringify
和json_decode
:并且:
更新:
...但如果您确实想使用它们,那么:
和:
You can avoid to use
JSON.stringify
andjson_decode
:And:
Update:
... but if your really want to use them, then:
And:
如果您想要关联数组,请将第二个参数传递为 true,否则它将继续返回对象。
Pass the second argument as true if you want the associative array otherwise it will keep returning object.
尝试:
因为
json_decode
的默认行为是返回stdClass
类型的对象。或者,将第二个可选的
$assoc
参数设置为true
:Try:
since
json_decode
's default behaviour is to return an object of typestdClass
.Alternatively, set the second optional
$assoc
argument totrue
:看起来 jQuery 可能会以 urlencoded 形式对 javascript 对象进行编码,然后将其填充到 $_POST 中。至少从他们的示例来看。我会尝试将您的对象传递到
post()
中而不对其进行字符串化。It looks like jQuery might encode a javascript object in urlencoded form then would be populated into $_POST. At least from their examples. I'd try passing in your object into
post()
without stringifying it.如果你想使用 json 数据作为关联数组,你可以尝试如下:
If you want to use json data as an associative array, you can try as following: