jquery - JSON字符串循环问题

标签 jquery ajax arrays json

我有一个 json 字符串

[{"part_id":"66","part_name":"Palet crate","part_image":"crate-box.gif","0":{"language_data_content":"Length [mm]","pgd_value":"1000"},"1":{"language_data_content":"Width [mm]","pgd_value":"800"},"2":{"language_data_content":"Height [mm]","pgd_value":"800"},"3":{"language_data_content":"Thickness [mm]","pgd_value":"20"}}]

这是我在 Controller 中的操作的 Ajax 响应的一部分

  for($i=0;$i<count($partlist);$i++){              
            $jsondata[$i]['part_id'] = $partlist[$i]['part_id'];
            $jsondata[$i]['part_name'] = $partlist[$i]['part_name'];
            $jsondata[$i]['part_image'] = $partlist[$i]['part_image'];
            $gdata = $pgdata->getPropertyDimensions($partlist[$i]['part_id'],1);
            if(count($gdata) > 0){
                $j = 0;
                foreach($gdata as $g){
                    $jsondata[$i][$j]['language_data_content'] = $g->language_data_content;
                    $jsondata[$i][$j]['pgd_value'] = $g->pgd_value;
                    $j++;
                }
            }           
        } 
       echo json_encode($jsondata);exit;

对于一个部件 ID,可以有多个 pgd_value 在这个 json 数组中,只有一个部件 id 和四个 pgd_value..在我的 ajax 成功函数中循环这个 json如

success:function(msg){
str = '';
  if(msg.length > 0){
                for(j=0;j<msg.length;j++){
   str +='<span>'+msg[j]['part_id']+'</span>';
   // here i want to loop those four **pgd_value** values from json is it possible ?

}
}

}

最佳答案

var msg = [{
    "part_id": "66",
    "part_name": "Palet crate",
    "part_image": "crate-box.gif",
    "0": {
        "language_data_content": "Length [mm]",
        "pgd_value": "1000"
    },
    "1": {
        "language_data_content": "Width [mm]",
        "pgd_value": "800"
    },
    "2": {
        "language_data_content": "Height [mm]",
        "pgd_value": "800"
    },
    "3": {
        "language_data_content": "Thickness [mm]",
        "pgd_value": "20"
    }}];
    var data = msg[0]; // extract the whole object from array
    // loop over object
    for (var key in data) {
        // checking for key which contain pgd_value
        // as you mentioned about only 4 pgd_values 
        // so here is the checking for just 4 index
        if (key == '0' || key == '1' || key == '2' || key == '3') {
            // here I used square bracket notation to 
            // retrieve data from object
            alert(data[key].pgd_value);
        }
    }

<强> DEMO

关于jquery - JSON字符串循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11044657/

相关文章:

if语句中的Python数组元素

javascript - 数组切片最后 1500 个数组元素 - Javascript

jquery - IndexOf 和数组 - 优化此 jQuery 代码的最佳方法是什么?

javascript - Gmail 发送按钮上的 event.PreventDefault

javascript - 通过多个链接从多个隐藏字段更新 1 个文本区域

javascript - 如何通过许多重复出现的图像来加快页面加载时间?

javascript - 如何使用 Google Analytics 跟踪 AJAX GET 请求和 PDF 下载?

jquery - 在 jQuery 中执行未知数量的 Ajax 请求

javascript - 如何知道JS文件中的 Action 类型

jquery - 如何处理 Ajax JSON 响应?