如何使循环中的多个ajax请求依次返回值? [英] How to make Multiple ajax requests in a loop return values sequentially?

查看:26
本文介绍了如何使循环中的多个ajax请求依次返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在循环中发出一系列 Ajax 请求.其中大约 100 个.每个请求都返回一个 JSONP 变量.我从 JSON 中提取数据并不断将值附加到 div 中.问题是我希望 div 按照函数调用的顺序附加数据.即依次.现在,我每次刷新页面时都会得到不同的顺序,具体取决于请求完成的顺序.这是我的代码.

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 有时.我什至尝试 async: false .那没有帮助.我在某处读到 JSONP 不能用 async: false 完成.请帮帮我.

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.

推荐答案

您可以使用占位符.

  $.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);
            }

        });
});

这篇关于如何使循环中的多个ajax请求依次返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆