我正在使用JSON以变量名返回彼此相同的对象数组,但值不同。有没有一种方法可以将对象放在JSON对象中,以便我可以引用它们,如data.1.name,data.2.name等?
当前(可怕的)代码:
$(document).ready(function(){
var data = 'manliness=' + $("#manliness_level_number").html() + '&type=enemy';
load_opponents();
function load_opponents()
{
$.getJSON('http://arflux-rpg.com/game/index.php/handler/request', data, function(data){
if (data.success == true)
{
$("#enemy_list").append("<div id='" + data.name + "' class='enemy'><img class='enemy_image' src='http://dummyimage.com/100x100/000/fff&text=100x100' /><div class='enemy_manliness'>" + data.manliness + "</div><div class='enemy_richliness_reward'>"+data.richliness_reward+"</div><div class='enemy_manliness_reward'>"+data.manliness_reward+"</div></div>");
}
else
{
alert('Failed to load enemies and users! ' + data.err);
}
});
}
[code cut from here for brevity]
答案 0 :(得分:1)
将对象放入数组中,然后将数组转换为JSON。然后,您可以data[1].name
和data[2].name
等方式访问它们。
答案 1 :(得分:1)
你可能想要一个数组:
var data = [ { "name": "one"},
{ "name":"two"},
{ "name":"three"} ];
然后像这样引用它:
data[i].name;
答案 2 :(得分:1)
只需将响应数据推送到数组中:)
var myArray = [];
$.getJSON('http://arflux-rpg.com/game/index.php/handler/request', data, function(data){
if (data.success == true) {
myArray.push(data);
} else {
alert('Failed to load enemies and users! ' + data.err);
}
});
就这么简单:)