2017-01-04 18 views
0

我通過從不同的JSON URL提取值來創建表。對於第一個JSONUrl(PoolsUrl),一切正常。對來自第二個JSON URL(RoundsUrl)的數據應用同一個表並不合適。正確的數據被返回,但附加在表格的最後一行(見下圖)。 RoundsUrl是使用PoolsUrl中的JSON值創建的。JSON數據沒有正確地附加到使用JavaScript的表格

爲什麼添加在最後一行的'創建回合'列的數據如下圖所示?

$(document).ready(function() { 
my_pools = {} 
$.getJSON(PoolsUrl, 
     function (json) { 
      my_pools = json; 
      createdRounds = {} 
      my_pools.createdRounds = { 
       "CreatedRounds": "none" 
      } //created this key and value to add number of rounds in the pool JSON properties. 
      var tr; 
      for (var i = 0; i < my_pools.length; i++) { 
       tr = $('<tr/>'); 
       tr.append("<td>" + my_pools[i].poolId + "</td>"); 
       tr.append("<td>" + my_pools[i].name + "</td>"); 
       tr.append("<td>" + my_pools[i].totTeams + "</td>"); 
       my_poolIdString = my_pools[i].poolId.toString() 
       RoundsUrl = url + my_poolIdString 
       $.getJSON(RoundsUrl, //output: {"1":"Round 1","2":"Round 2"} 
        function (json) { 
         my_roundsCreated = json; 
         my_roundsCount = Object.keys(my_roundsCreated).length 
         my_pools.createdRounds = my_roundsCount; 
         tr.append("<td>" + my_pools.createdRounds + "</td>") 
        }) 
       $('table').append(tr); 
       } 
      }) 
}); 

PoolsUrl和RoundsUrl自己都在這裏留下了,但這些正常工作。返回JSON值。

問題可能是第二個$ .getJSON函數中的變量'my_pools.createdRounds'沒有引用我的全局my_pools對象。

輸出表圖像:

Why is "rounds created"column not appended properly?

+0

可能是因爲它是異步的...... – epascarello

回答

0

的問題是,你有一個異步調用的事實。變量tr被共享,並且在呼叫返回時,tr是不同的元素。

在for循環中移動tr聲明。

var tr = $('<tr/>'); 
+0

感謝您的幫助@epascarello。你的建議確實解決了這個問題。沒有改變。 – Jelle

+0

你的評論沒有意義。它說它解決了你的問題,但它沒有。那麼你是否在裏面聲明變量不再被共享? – epascarello

+0

ai這是一個痛苦的錯字,你的建議並沒有解決問題。抱歉的混淆。 – Jelle