2010-10-16 20 views
1

好的,這個問題很奇怪。我正在使用getJSON()接收項目列表。對於每個返回的項目,我再次使用getJSON()執行查找。在返回第二次查找時,我嘗試將for循環範圍內的變量追加到DOM,但輸出是同一個。奇怪的是,當我在第二個getJSON()之前發出變量的alert()時,變量就像它應該改變一樣。jQuery的非常奇怪的行爲getJson()不改變循環中的值

這是一個錯誤?好像是的getJSON緩存的東西...

$.getJSON(
"http://someurl", 
    function(data) { 
     var items = data.items; 

     for(i=0; i<items.length; i++) { 
      var i = items[i]; 
      //when doing an alert of 'i' here, it changes... 
      $.getJSON(
       "http://anotherurl", 
        function(r) { 
         $("#feed").append(i.some_property); 
         //appended item should be different upon each loop 
         //but ends up appending the same thing every time!! 
        } 
      ) 
     } 
    } 
) 

回答

4

Ajax是異步。

在內部getJSON發出的第一個HTTP請求返回之前,您可能會設法通過外部循環進行循環,因此i位於內部回調第一次運行之前的最後一個值。

當您添加alert時,循環執行會暫停,直到您單擊確定按鈕並且這會給HTTP請求響應時間。

您需要在不同範圍內創建新的i(或其他變量)。

for(var i=0; i<items.length; i++) { 
    // IMPORTANT: Don't forget to use var. 
    // DO NOT use globals without a very good reason 
    // Oh, i is a var but you use the keyword on the *second* time you use it 
    // Don't do that, it's confusing! 
    do_the_inside_thing(items[i]); 
} 

function do_the_inside_thing(foo) { 
    // A new function is a new scope 
     $.getJSON(
      "http://anotherurl", 
       function(r) { 
        $("#feed").append(foo.some_property); 
       } 
     ); 
} 
+0

我有這樣的感覺。你的回答證實了這一點。 – trinth 2010-10-16 05:23:38

+0

實際上,當我使用console.log時,輸出結果也不同 – trinth 2010-10-16 05:37:14

+0

,thx爲'var'關鍵字提醒。我一直在使用python一段時間,剛回到JS爲一個小應用程序。 – trinth 2010-10-16 05:40:39

0

不應該引用傳遞給內部Json請求的數據「r」嗎?這應該包含不同的數據。否則,您每次都會收到相同的外部響應數據「i」。

+0

我從第二個getJSON()中抽取了一些代碼來簡化這裏的代碼,因此它看起來沒有被使用。 – trinth 2010-10-16 05:24:22