2011-10-24 64 views
3

因此,我發佈了一個JSON字符串中的對象數組使用JavaScript到PHP腳本,我有真正的問題在PHP解碼。在PHP中解碼JSON數組對象,它是反斜槓嗎?

我的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 

我真不明白什麼愚蠢的錯誤,我做,是什麼做的反斜槓?

任何幫助非常感謝!

感謝, -Ben

+0

打印$ data值,看看json_decode後這個變量的值是多少... – Dev

回答

11

使用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並重新啓動服務器。

+0

Simone你是我的救世主,我愛你。謝謝! :D – bbeckford

+1

雖然顯然是一個有效的答案,但這與戰鬥的症狀而不是原因:magic_quotes_gpc。把它們關掉,你再也不用擔心這樣的事情了。 –