2012-09-25 32 views
0

所以我想獲得一系列的json結果,以使用innerHTML呈現在div標記內。基本getJSON in for循環與innerHTML問題

<script> 
    $(document).ready(function() { 
     var html2 = ''; 
     var thread_id = ''; 
     var created_thread_ids = new Array(123123, 12312312, 1231222); 
     for (var i in created_thread_ids) 
     { 
      thread_id = created_thread_ids[i]; 
      $.getJSON(ravenUrl + '/docs/threads/' + thread_id, function(thread){ 
       html2 += '<div class="result">' + thread.Title + thread_id + '</div>'; 
       document.getElementById("showit").innerHTML = html2; 
      }); 
     } 
    }); 
    </script> 

    <div id="showit"></div> 

我的問題是,可變thread.Title完美的作品,但變量的thread_id只有當它的url和找到正確的網址,但第二次它顯示了相同的ID後,每工作在第一時間線。就像這樣:

<div id="showit"> 
<div class="result">This is the first title123123</div> 
<div class="result">This is the second title123123</div> 
<div class="result">This is the third title123123</div> 
</div> 

回答

1

您傳遞給$.getJSON方法的回調函數是一個閉包,因爲該方法是異步的,所以它將在執行時使用值thread_id。這是一個常見的問題,並且有幾種解決方法,最常見的是使用包裝函數:

for (var i in created_thread_ids) 
    (function(i){ 
    ... 
    var thread_id = created_thread_ids[i]; 
    $.getJSON(ravenUrl + '/docs/threads/' + thread_id, function(thread){ 
    html2 += '<div class="result">' + thread.Title + thread_id + '</div>'; 
    document.getElementById("showit").innerHTML = html2; 
    }); 
    ... 
    }(i)); 
} 

...或只是...

for (var i in created_thread_ids) { 
    var thread_id = created_thread_ids[i]; 
    $.getJSON(ravenUrl + '/docs/threads/' + thread_id, 
    (function(thread_id) { 
      return function(thread) { 
       html2 += '<div class="result">' + thread.Title + thread_id + '</div>'; 
       document.getElementById("showit").innerHTML = html2; 
      }; 
    }(thread_id)) 
); 
} 

一點題外話,我強烈推薦使用方便的for(;;)替代(for..in)構造,當它用於遍歷數組時(或者,可以考慮使用$.each有用的jQuery方法)。

+0

非常感謝你:) – Niko

0

created_thread_ids是一個字符串,它應該是一個數組。

變化

var created_thread_ids = '123123, 12312312, 1231222'; 

var created_thread_ids = new Array(123123, 12312312, 1231222); 
+0

我真的很感激你的答案,但它實際上是一個數組,它是在代碼中早些時候收集的,當我試圖在這裏簡化它在stackoverflow時,我意外地在代碼示例中使它成爲一個字符串。抱歉!我向你保證,它是唯一從真實代碼中改變的東西。 – Niko

+0

請用正確的代碼更新您的問題。 –

0

首先,穆特說,你應該使用數組,而不是字符串

var createdThreadIds = [123123, 12312312, 1231222] 

其次,你的代碼異步,你不知道來自你的ajax調用的回調如何,它們可以混合起來。

第三,我會建議你使用由ajax調用返回的Deffered對象,並且僅在執行所有調用時更新DOM。

+0

我明白爲什麼它不會工作得益於你的指針,但我真的不知道如何讓它實際工作... – Niko