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.

    评论

报告相同问题?