2013-03-27 41 views
1

我有如何使用jQuery

[ 
    { 
     id: 15, 
     diemdung: "a" 
    }, 
    { 
     id: "16", 
     diemdung: "b", 
     khoangcach: "300", 
     pho: "c", 
     da: [ 
      { 
       lancan: "d", 
       kc: "333" 
      }, 
      { 
       lancan: "e", 
       kc: "322" 
      } 
     ] 
    }, 
    ... 
] 

我使用PHP像print json_encode($rows);
像JSON格式,我尝试在客户端读取它使用jQuery像

$.getJSON(url,function(json){ 
    $.each(json,function(key, val){ 
     $.each(this.da,function(){ 
      alert(this.kc); 
     }); 
    }); 
}); 
阅读多层次JSON格式

但它不起作用。我该怎么做?感谢

回答

1

如果您的代码工作,不然,你可能会得到以下错误:

TypeError: obj is undefined 

这是因为外部数组中的第一个对象没有“da”属性的值。在尝试遍历由“da”属性持有的数组之前,您应该检查它是否存在。

尝试:

$.getJSON(url,function(json){ 
    $.each(json,function(){ 
     if (this.da) { 
      $.each(this.da,function(){ 
       alert(this.kc); 
      }); 
     } 
    }); 
}); 
0
$.each(json, function(arrayID, arrayVal) { 
    //alert(arrayVal.id); 
    $.each(arrayVal.da, function(daKey,daData) { 
    alert(daData.kc); 
    }); 
}); 

我的继承人一样的,所以质疑前一阵子进一步代码

JQuery $.each() JSON array object iteration

编辑重新命名一些变量来更清楚

+0

什么警示说明了什么? – 2013-03-27 02:45:44

+0

应该在每次遇到json数组中的“kc”节点值时发出警报,如果警报是alert(arrayVal.id + daData.kc)将显示第一个每个+ kc嵌套节点val的id节点,请感谢 – 2013-03-27 02:52:22

+0

谢谢所有但它不适合我。我尝试@john S答案,它工作:) – DeLe 2013-03-27 03:20:29

0

对于n层次结构

var str = '{"countries":[{"name":"USA","grandfathers":[{"gFName":"Steve","grandfathersKid":[{"gFKName": "Linda","kid": [{"name": "Steve JR", "friends": [{"name": "Kriss|John|Martin|Steven"}]}]}]}]}]}'; 
var obj = jQuery.parseJSON(str); 
parseJsonString(obj); 

功能:

function parseJsonString(data){  
    $.each(data, function(index, val){ 

     if($.type(val) == 'object' || $.type(val) == 'array'){ 
      product.parseJsonString(val); 
     }else{ 
      alert(index + ' - ' + val); 
     } 

    }); 
}