我有这样的数据:
{
"1":{
"id":"1",
"boarding":"",
"atak":"3",
"pw":4,
"zwrotnosc":3,
"marynarze":130,
"zolnierze":0},
"2":{
"id":"2",
"boarding":"",
"atak":"5",
"pw":4,
"zwrotnosc":4,
"marynarze":0,
"zolnierze":222}
}
我试过(我在数据中),或者(i = 1; i< data.length; i ++),但这是错误的。
拥有像php foreach这样的东西,或者像数组数据一样处理它会很好[1] [pw]
编辑:
当我做循环时,我得到了194次迭代,数据[i]保存了数据中的单个字符。
EDIT2:
这是我在json响应之前的数据:
Array
(
[1] => Array
(
[id] => 1
[boarding] =>
[atak] => 2
[pw] => 4
[zwrotnosc] => 4
[marynarze] => 146
[zolnierze] => 0
)
[2] => Array
(
[id] => 2
[boarding] =>
[atak] => 5
[pw] => 5
[zwrotnosc] => 5
[marynarze] => 0
[zolnierze] => 250
)
)
我用
echo json_encode($players);
EDIT3:
看起来像这样: http://img20.imageshack.us/img20/4798/screenwlz.png
JSON看起来不错: http://img822.imageshack.us/img822/2871/screenmuj.png
编辑:已解决
确定。感谢
它有所帮助:
data = jQuery.parseJSON( data );
for (i in data){
// code
}
答案 0 :(得分:2)
你可能只是没有意识到JS for
在密钥上进行迭代。
for(var key in data) {
var value = data[key];
// do stuff
}
答案 1 :(得分:1)
您需要运行嵌套的for
循环:
// var data = <?php echo json_encode($players); ?>;
// ^ ^
// +----------------------------------+---- no quotes
var data = {
"1": {
"id": "1",
"boarding": "",
"atak": "3",
"pw": 4,
"zwrotnosc": 3,
"marynarze": 130,
"zolnierze": 0
},
"2": {
"id": "2",
"boarding": "",
"atak": "5",
"pw": 4,
"zwrotnosc": 4,
"marynarze": 0,
"zolnierze": 222
}
}
for (var i in data) {
for (var j in data[i]) {
console.log("data[" + i + "][" + j + "]", data[i][j]);
}
}