所以我在JSON字符串中使用javascript发布对象数组到PHP脚本,我在PHP中解码它有真正的问题。
我的javascript代码如下:
$.ajax({
type: 'POST',
url: "question_save.php",
data: {myJson: JSON.stringify(jsonArray)},
success: function(data){
alert(data);
}
});
发送给PHP的字符串看起来像这样:
[{"content":"Question text"},{"answerswerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerswerContent":"","score":"0","responseChecked":0,"responseContent":""}]
如果我回显$_POST['myJson']我得到这个:
[{'"content'":'"Question text'"},{'"answerswerContent'":'"Some answer text'",'"score'":'"234'",'"responseChecked'":0,'"responseContent'":'"'"},{'"answerswerContent'":'"'",'"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
我真的不明白我犯了什么愚蠢的错误,是和后斜杠有关吗?
任何帮助都非常感谢!
谢谢,本
使用stripslashes ( $string )
- http://php.net/manual/en/function.stripslashes.php
应该可以
$json = $_POST['myJson'];
$json_string = stripslashes($json)
$data = json_decode($json_string, true);
// simple debug
echo "<pre>";
print_r($data);
但是,正如其他人已经指出的那样,最好禁用magic_quotes_gpc
。
打开php.ini
文件并搜索这一行:
magic_quotes_gpc = On
设置为"Off
",重启服务器
这与魔术引号有关
最好是禁用这个恼人的旧功能,忘记那些问题。您可以按照以下说明禁用。