我做了一個個人項目,我可以在搜索欄中輸入電影標題並獲取有關它們的信息。數據在使用omdb的api的json中。下面是代碼的主要部分:在動態創建的div中創建分區
//film[] is an array of strings contains movie titles
//this array works perfectly giving me 0 through lenght-1 elements
for(var i= 0; i< film.length; i++)
console.log(i+" : "+film[i]);
console.log("Film you entered is "+ film);
//#load is section element that is use to display "loading" while the data is recieved
$('#load').html("<h2>LOadiNG.....................</h2>");
//looping for each movie
for(var j= 0; j< film.length; j++){
$.getJSON("http://www.omdbapi.com/?t="+film[j]+"&y=&plot=short&r=json", function(json) {
//does not work if I give 3 titles, shows "processing 3 : undefined" all the time
console.log("processing "+j+" : "+film[j]);
/*
*#info is section element where the data is displayed
*".for-info" styles each div child inside section so that each movie has a visible seperation
*(this is what I want)
*/
$("#info").append("<div id="+j+" class='for-info'></div>");
$('#load').empty();
//append each key-value in its particular div
for(val in json)
$("#"+j).append('<p>'+val+' --> '+json[val]+'</p>');
$("#"+j).append("<p><br/></p>");
});
所以我的問題是如何創建使用DIV使得每個電影數據是1個特別格在部分師?另外我注意到,有時候索引較高的電影會在較低索引之前被檢索出來。當我使用循環來控制它時,這怎麼可能?
可以,因爲它使用異步方法,有時意爲檢索結果可能需要更長的等待時間大約一個電影具有更高的索引檢索數據和結果可能會略有不同的順序(被退回,因爲代碼繼續,而不是停止並等待返回的值,然後繼續)。爲了避免這種情況,可能需要將數據抓取到本地數組,並且一旦完成迭代該數組。 –
'getJSON()'是_asynchronous_,所以您可能會以不同於發送請求的順序獲得您的響應。 – dave