George_Fal 2015-02-06 11:31 采纳率: 0%
浏览 7

顺序执行js

I am developping a project that needs to deal with ajax calls in a sequential manner. The code I have is something like:

for(var j=0; j<3;j++) {
                $.ajax({
                    url:url[j],
                    async:false
                }).done(function(result){
                    var data = result.data;
                    for(var i=0; i < data.length;i++){
                        analyses += "<div><div id=\"" + data[i] + "\" class=\"module\">";
                        analyses += "<br/>Analysis : " + data[i] + "<br/>";
                        analyses += "</div></div>";
                        $("#analysesPlaceHolder").html(analyses);
                    }
                });

            }

However, now it just randomly selects the url from the list (sometimes it is the first, sometimes it is not). How can a make the execution sequential so that the code first performs the first ajax call, then the second etc.

  • 写回答

1条回答 默认 最新

  • 普通网友 2015-02-06 19:41
    关注

    I would not recommend using ajax calls within a loop.

    Here is a better way, which increments the count in the ajax callback, then fires the next ajax request:

    var urlCount = 0;
    
    var makeAjaxCall = function(count) {
        $.ajax({
            url:url[count],
        }).done(function(result){
            var data = result.data;
            for(var i=0; i < data.length;i++){
                analyses += "<div><div id=\"" + data[i] + "\" class=\"module\">";
                analyses += "<br/>Analysis : " + data[i] + "<br/>";
                analyses += "</div></div>";
                $("#analysesPlaceHolder").html(analyses);
            }
    
            urlCount++;
            if (urlCount < 3) {
                makeAjaxCall(urlCount);
            }
        });
    }
    
    makeAjaxCall(urlCount);
    

    You could also chain ajax calls using promises, as stated in the comment above.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题