推送功能在嵌套json调用中不起作用(使用jquery从多个API)

时间:2019-05-21 18:14:19

标签: javascript jquery html ajax getjson

我想使用多个JSON API创建HTML表。这些API相互依赖,因此我必须对它们进行嵌套的getJSON调用。

我使用了嵌套的getJSON调用。但是,只有外部推送有效,而内部推送无效。这就是为什么在创建的表中仅显示城市名称的原因。

在代码中稍作修改

var tr;
   $( document ).ready(function() {
      $.getJSON("project.json", function(data){ 
          $.each(data, function(key, value){
            tr = [];
      tr.push('<tr>');
     $.each(value, function(key1, value1){
        $.getJSON("builder.json", function(data2){
        $.each(data2, function(key2, value2){
            if (key2 == key){
                //console.log(value2);
                 tr.push('<td>'+ (value2) +'</td>');
                 return;
            }
        });
      });
        tr.push('<td>'+ (value1.project) +'</td>');
        //console.log(value1.project);
        $.getJSON("city.json", function(data3){
        $.each(data3, function(key3, value3){
            if (key3 == value1.city){
                //console.log(value3);
                 tr.push('<td>'+ (value3) +'</td>');
                 return;
            }
        });
      });
        $.getJSON("price.json", function(data4){
        $.each(data4, function(key4, value4){
            if (key4 == value1.project_id){
                //console.log(value4);
                 tr.push('<td>'+ (value4) +'</td>');
                 return;
            }
        });
      });
     });
      tr.push('</tr>');
      $('#emp').append($(tr.join('')));
  });
 });
});

表如下:

<table id="emp">
  <tr>
    <th>Builder</th>
    <th>Project</th>
    <th>City</th>
    <th>Price</th>
  </tr>  

API给出为:

builder.json

{
    "1":"alamiz builder",
    "2":"souroy builder",
    "3":"vin selv builder",
    "4":"gol mat builder",
    "5":"sm dev builder",
    "6":"zahi builder"
}    

city.json

{
    "1":"mumbai",
    "2":"delhi",
    "3":"pune",
    "4":"banglore"
}

project.json

{
   "1":[
       {"project_id":1,"project":"Alamiz City","city":1},
       {"project_id":2,"project":"Alamiz Tech City","city":1},
       {"project_id":3,"project":"Alamiz Down Town","city":3},
       {"project_id":10,"project":"Alamiz Nature","city":2}
   ],
   "3":[
       {"project_id":4,"project":"The Tech Sky","city":1},
       {"project_id":5,"project":"Alphonso","city":1}
   ],
   "4":[
       {"project_id":6,"project":"Royal Tech","city":4},
       {"project_id":7,"project":"Future City","city":4}
   ],
   "6":[
       {"project_id":8,"project":"Zahi Skyline","city":1}
   ],
   "2":[
       {"project_id":9,"project":"Souras City","city":4}
   ]
}    

price.json

{
   "1":"2cr",
   "2":"3.5cr",
   "3":"1cr",
   "4":"2cr",
   "5":"4cr",
   "6":"4cr",
   "7":"5cr",
   "8":"3cr",
   "9":"7cr",
   "10":"6cr"
}

1 个答案:

答案 0 :(得分:-2)

$。each是异步的,当它在for循环(是同步的)内运行时,for循环在触发任何回调之前完成。

https://api.jquery.com/each/