2012-05-07 73 views
2

我有一組結果的,我已經使用PHP json_encode函數轉換爲JSON現在我想這個結果作爲JS數組,但我沒有得到一個想法,要做到這一點。JSON字符串到JS數組

我的PHP數組是這樣的:

Array 
(
    [latestRating] => Array 
     (
      [456] => Anonymous has rated xxx9 
      [457] => Anonymous has rated xxxx8 
      [458] => Anonymous has rated xxxx3.5 
     ) 

    [latestUser] => Array 
     (
      [242] => xxxxhas just signed up 
      [243] => xxxxxhas just signed up 
      [244] => xxxxxxhas just signed up 
     ) 

) 

當我在此做一個PHP json_encode函數我獲得以下字符串

{"latestRating":{"456":"Anonymous has rated mermaidbl00d 9","457":"Anonymous has rated GeorgiaHallx 8","458":"Anonymous has rated smithjhon 3.5","459":"Anonymous has rated Emilyxo 8.5","460":"Anonymous has rated leona 10","461":"Anonymous has rated leona 10","462":"Anonymous has rated W0rthlessliar 8","463":"Anonymous has rated Yousamsuck 9","464":"Anonymous has rated Aimeeerobbb 9","465":"Anonymous has rated lauramillerx 10","466":"Anonymous has rated tomwaz 1","467":"Anonymous has rated W0rthlessliar 1","468":"Anonymous has rated W0rthlessliar 1","469":"Anonymous has rated W0rthlessliar 1","470":"Anonymous has rated W0rthlessliar 1"},"latestUser":{"242":"rhiwilliamsx has just signed up","243":"W0rthlessliar has just signed up","244":"rebeccaronan has just signed up"}} 

我試圖透過JSON.stringify然後jQuery.makeArray也從中創建一個數組。 然後我試着eval('['+ string +']'),但沒有一個幫助。

我是一個JSON一個新手無法找到適當的支持。

Regards Himanshu Sharma。

回答

3

使用JSON.parse()代替JSON.stringify
拳頭是JavaScript的等同於PHP的json_decode,後者相當於json_encode

注意:如果您使用jQuery.ajaxdataType: 'json',則回調中的參數已經是解碼對象。

在你的代碼中,PHP「陣列」是不是一個JavaScript數組,而是一個對象。

+0

好吧,我很抱歉,我沒有注意到,我們曾在阿賈克斯too.I該數據類型的選擇會得到從那裏JSON字符串以及我們如何訪問它在JS?當我提醒它,它說的object.So我試過點符號,但沒有成功,我需要它作爲一個數組。 –

+1

正如我所說的,你傳遞的對象是**而不是數組,而是一個對象。你的回調的例子:'function(data){alert(data.latestRating ['456']);}'。 –

+0

對不起Rob我有點天真this.json_encode給出了一個數組的json對象是正確的我得到it.data.latestRating ['456']將給我的元素.LatestRating實際上是一個索引在這裏有一個數組和我想要在js中迭代,那麼我們該怎麼做呢?對不起,如果這是一個愚蠢的問題,但我有點困惑。 –

2

應該已經準備好,如果你正在使用json_encode()去,如果不行,用JSON.parse()。您還可以查看當你呼應的數據PHP頭包括:

header('Content-type: application/json'); 

如果它是從一個Ajax響應回來,只是參考的對象,像這樣:

success : function(data) { 
    console.log(data.latestRating); 
}