【发布时间】:2011-12-13 23:13:49
【问题描述】:
所以我使用 javascript 将 JSON 字符串中的对象数组发布到 PHP 脚本,但在 php 中解码它时遇到了真正的问题。
我的javascript如下:
$.ajax({
type: 'POST',
url: "question_save.php",
data: {myJson: JSON.stringify(jsonArray)},
success: function(data){
alert(data);
}
});
发送到 PHP 的字符串如下所示:
[{"content":"Question text"},{"answerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerContent":"","score":"0","responseChecked":0,"responseContent":""}]
如果我回显 $_POST['myJson'] 我会得到:
[{\"content\":\"Question text\"},{\"answerContent\":\"Some answer text\",\"score\":\"234\",\"responseChecked\":0,\"responseContent\":\"\"},{\"answerContent\":\"\",\"score\":\"0\",\"responseChecked\":0,\"responseContent\":\"\"}]
然而,当我想解码 JSON 并像这样循环遍历它时......
$json = $_POST['myJson'];
$data = json_decode($json, true);
foreach ($data as &$value) {
echo("Hi there");
}
...我收到此错误:
Warning: Invalid argument supplied for foreach() in /home/thecrime/public_html/test1/question_save.php on line 15
我真的不明白我在犯什么愚蠢的错误,这与反斜杠有关吗?
非常感谢任何帮助!
谢谢, -本
【问题讨论】:
-
打印 $data 值,看看 json_decode 之后这个变量的值是多少 ...