我做了一个个人项目,我可以在搜索栏中输入电影标题并获取有关它们的信息。数据在使用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