2

我有一组结果,我已使用 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 的新手,也找不到合适的支持。

问候希曼舒夏尔马。

4

2 回答 2

3

使用JSON.parse()而不是JSON.stringify.
拳头是 JavaScript 的等价于 PHP 的json_decode,后者等价于json_encode.

注意:如果你使用jQuery.ajaxwith dataType: 'json',那么回调中的参数已经是一个解码的对象。

在您的代码中,PHP“数组”不是 JavaScript 数组,而是一个对象。

于 2012-05-07T18:57:17.860 回答
2

如果您正在使用它应该已经准备好使用json_encode(),如果没有,请使用JSON.parse(). 您还可以在回显要包含的数据时检查 PHP 标头:

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

如果它是从 ajax 响应中返回的,只需像这样引用该对象:

success : function(data) {
    console.log(data.latestRating);
}
于 2012-05-07T18:57:01.017 回答