循环访问Javascript中的Object来自PHP

时间:2014-05-29 11:48:47

标签: javascript php jquery ajax

您好我有一个返回以下JSON的PHP脚本:

[
    {
        "zone_name": "1st_zone"
    },
    {
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152"
        ]
    },
    {
        "zone_name": "2nd_zone"
    },
    {
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152",
            "51.57707,0.11398",
            "51.48651,0.12497",
            "51.56939,0.28427"
        ]
    }
]

在Javascript中,我正在进行这样的AJAX调用:

$.ajax({
        type: "POST",
        cache: false,
        url: "load_zone.php",   
        dataType: 'json',
        success:function(response){
            for(var i =0; i<response.length; i++){
                console.log(response[i]);
            }
        },
        error:function(){
        }
    }); 

我在控制台中得到了这个结果:

Object { zone_name="1st_zone"}
Object { coordinates=[5]}
Object { zone_name="2nd_zone"}
Object { coordinates=[8]}

如何单独打印每个zone_name和坐标?

由于

2 个答案:

答案 0 :(得分:1)

for(var i =0; i<response.length; i++){
   if(i%2 === 0) console.log(response[i].zone_name);
   else console.log(response[i].coordinates); 
  // console.log(response[i].zone_name || response[i].coordinates); //one liner
}

这将为您提供相应的区域名称和坐标。 您当前的JSON有一个对象数组,它们将区域名称和坐标列为数组的连续元素。

但你应该尝试改变你的json看起来像这样:

[
    {
        "zone_name": "1st_zone"
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152"
        ]
    }
...
]

这意味着数组将包含表示带有坐标的区域的对象。然后可以访问response[i].zone_nameresponse[i].coordinates

答案 1 :(得分:0)

这样做:

$.each(data,function(index,item){

    console.log(item);
    $.each(item,function(index1,item1){
    console.log(item1);
    });

FIDDLE