如何使在一个循环的返回值连续多Ajax请求?返回值、Ajax

2023-09-10 21:11:21 作者:Warm-boy

我必须做出一系列的循环Ajax请求。其中约100。而每个请求返回一个JSONP变量。我从提取的JSON数据,并保持附加价值变成一个div。问题是,我想股利与函数调用的订单数据被追加。即顺序。现在我得到不同的顺序每次我刷新页面,这取决的请求完成的顺序。这是我的code。

I have to make a series of Ajax requests on a loop. Around 100 of them. And each request returns a JSONP variable. I extract data from the JSON and keep appending the value into a div. The problem is that I want the div to be appended with data in the order of function call. i.e sequentially. Now i get a different order everytime i refresh the page depending on the order in which the request completes. Here's my code.

  $.each(elem, function (index, item) {

            $.ajax({
                type: 'post' ,
                url: moviesSearchUrl + '&q=' + encodeURI(item) + '&page_limit=1',
                dataType: "jsonp",
                async: false, 
                success: searchCallback
            });

            function searchCallback(data) {
                var movies = data.movies;

                var markup = index + ': '+   movies[0].title + '<img class=" bord" src="' + movies[0].posters.thumbnail + '" /><br/>';

                $("div.content").append(markup);
            }

        });
});

由于我是显示DIV中的索引值,每次我看到一些随机的订单。 2 4 3 1 7有时和1 5 2 7 4的时候。我甚至尝试异步:假的。那不帮助。我读的地方,JSONP不能与异步完成:假的。请帮助我。

As i am displaying the value of the index inside the div, everytime i get random orders . 2 4 3 1 7 sometimes and 1 5 2 7 4 sometimes. I even tries async: false . That doesnt help. I read somewhere that JSONP cannot be done with async: false . Please help me out.

推荐答案

您可以使用一个占位符。

You could use a place-holder.

  $.each(elem, function (index, item) {

            var $placeholder = $('<div>').appendTo("div.content");

            $.ajax({
                type: 'post' ,
                url: moviesSearchUrl + '&q=' + encodeURI(item) + '&page_limit=1',
                dataType: "jsonp",
                async: false, 
                success: searchCallback
            });

            function searchCallback(data) {
                var movies = data.movies;

                var markup = index + ': '+   movies[0].title + '<img class=" bord" src="' + movies[0].posters.thumbnail + '" /><br/>';

                $placeholder.replaceWith(markup);
            }

        });
});