开发者

Synchronous JQuery.post()

I'm writing a little script that makes individual AJAX calls through a loop and I came across a, 开发者_如何学JAVAmost likely obvious, problem. It seems that the loop is going to fast to handle the data that is received with ajax, causing it to only load the last piece of data in the loop. I added an alert box that steps through the iterations and that loads the data fine, but it wouldn't be practical in a user environment. The code is simply a jquery .post() with a callback inside a for-loop. I can post code upon request, but I feel like this can be cleared up verbally. Any one know a workaround or better approach to loading data sequentially?

EDIT

Does .ajaxSetup() modify .post()? Perhaps I can use that to change the async value for .post()..


You need to force your ajax call to be synchronous my friend ;)

http://api.jquery.com/jQuery.ajax/

ex:

asyncBoolean Default: true

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.


I actually found that adding this snippet worked so I didn't have to change my .post() to .ajax()

$.ajaxSetup({ async: false });

I'm not sure if it will also change the settings of my other ajax calls though


If you use async: false you should be able to put each of your ajax calls into a queue until they get to be executed in a synchronous method. Like so:

 for( var i=0;i < x;i++ ){
     $.ajax({url: 'myurl',
             async: false,
             success: function(data){
                        //do something with the returned 'data'
                      };
    });
 }


function myFunction() {
    var x;
for(var i=0;i<10;i++){
    if (confirm("Press a button!") == true) {
        x = "You pressed OK!";
    } else {
        x = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = x;
}
}

    enter code here
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜