简体   繁体   English

使用相同 AJAX 函数的多个 AJAX 调用

[英]Multiple AJAX calls using the same AJAX functions

I am looking to fire off several jQuery AJAX requests in quick succession, so the response will not come before the next request.我希望快速连续发出几个 jQuery AJAX 请求,因此响应不会在下一个请求之前出现。 However, I do want to handle each one of these responses with the success function.但是,我确实想使用成功函数处理这些响应中的每一个。

With the following code, the first two responses will be ignored and only the last one will respond.使用以下代码,前两个响应将被忽略,只有最后一个响应。

$('#button').click(function() {
    var num = 3;
    for(var i=0;i<num;i++)
        ajaxCall(i);
}


function ajaxCall(data){
    $.ajax({
        url: '/echo/html/',
        success: function(msg) {
            alert(msg);
        }
    });
}

However I am trying to make it so that all three alerts would show up.但是,我正在努力使所有三个警报都显示出来。 It seems that each time the ajaxCall function is called it uses the same 'object' as it did the previous time instead of instantiating a new one, which is what I want to do.似乎每次调用ajaxCall函数时,它都使用与上一次相同的“对象”,而不是实例化一个新对象,这正是我想要做的。

Try this (using Deferred Object )试试这个(使用延迟对象

$('#button').click(function() {
    var num = 3;
    for(var i=0;i<num;i++) {
        ajaxCall(i).done(function(data) 
           { 
             alert(data) 
           }
        );
     }
});


function ajaxCall(data){
    return $.ajax({
        url: '/echo/html/'
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM