在PHP中解码JSON对象数组,它是反斜杠吗?

bbe*_*ord 3 php jquery json

所以我使用javascript将一个JSON字符串中的对象数组发布到PHP脚本中,并且我在php中解码它时遇到了实际问题.

我的javascript如下:

$.ajax({
    type: 'POST',
    url: "question_save.php",
    data: {myJson:  JSON.stringify(jsonArray)},
    success: function(data){

        alert(data);

    }
});
Run Code Online (Sandbox Code Playgroud)

发送给PHP的字符串如下所示:

[{"content":"Question text"},{"answerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerContent":"","score":"0","responseChecked":0,"responseContent":""}]
Run Code Online (Sandbox Code Playgroud)

如果我回复$ _POST ['myJson']我得到这个:

[{\"content\":\"Question text\"},{\"answerContent\":\"Some answer text\",\"score\":\"234\",\"responseChecked\":0,\"responseContent\":\"\"},{\"answerContent\":\"\",\"score\":\"0\",\"responseChecked\":0,\"responseContent\":\"\"}]
Run Code Online (Sandbox Code Playgroud)

然而,当我想解码JSON并像这样循环它...

$json = $_POST['myJson'];
$data = json_decode($json, true);

foreach ($data as &$value) {
    echo("Hi there");
}
Run Code Online (Sandbox Code Playgroud)

...我收到此错误:

Warning:  Invalid argument supplied for foreach() in /home/thecrime/public_html/test1/question_save.php on line 15
Run Code Online (Sandbox Code Playgroud)

我真的不明白我正在制造什么愚蠢的错误,是否与反斜杠有关?

任何帮助非常感谢!

谢谢,-Ben

Sim*_*one 13

使用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);
Run Code Online (Sandbox Code Playgroud)

但是,正如其他人已经指出的那样,最好禁用magic_quotes_gpc.

打开php.ini文件并搜索此行:

magic_quotes_gpc = On
Run Code Online (Sandbox Code Playgroud)

将其设置为Off并重新启动服务器.