我有一组结果,我已经使用php json_encode函数转换为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的新手也无法找到合适的支持。
此致 Himanshu Sharma。
答案 0 :(得分:3)
使用JSON.parse()
代替JSON.stringify
第一个是JavaScript相当于PHP的json_decode
,后者相当于json_encode
。
注意:如果您将jQuery.ajax
与dataType: 'json'
一起使用,则回调中的参数已经是解码对象。
在您的代码中,PHP“数组”不是JavaScript数组,而是对象。
答案 1 :(得分:2)
如果您使用json_encode()
,它应该已经准备好了,如果没有,请使用JSON.parse()
。您还可以在回显要包含的数据时检查PHP标头:
header('Content-type: application/json');
如果它从ajax响应中返回,只需像这样引用对象:
success : function(data) {
console.log(data.latestRating);
}