简体   繁体   English

重复jQuery Ajax调用

[英]Recurring jquery ajax calls

I have multiple check boxes for users to select and based on selected checkboxes i need to make a jquery ajax call. 我有多个复选框供用户选择,并且基于选定的复选框,我需要进行jquery ajax调用。 For that i used FOR loop to iterate through selected elements array and sent ajax request for each checkbox. 为此,我使用FOR循环遍历选定的元素数组,并为每个复选框发送了ajax请求。 Each request takes more than 5-10 minutes. 每个请求需要5-10分钟以上的时间。 In current scenario it calls all ajax request simultaneously. 在当前情况下,它同时调用所有ajax请求。

I want to call next ajax calls only after finishing earlier ajax request. 我只想在完成较早的ajax请求之后再调用下一个ajax调用。

Is there any solution for this? 有什么解决办法吗?

You can make recursive calls. 您可以进行递归调用。

function sendAjax(id) {
        var checkbox = $('input[type=checkbox]:eq('+id+')','#formid');
        if(checkbox == undefined)
             return;
        $.ajax({
            type: 'POST',
            dataType: "json",
            url: 'url',
            data: { },
            success: function (data) {
                  sendAjax(id+1);
            },
            error: function (data) {
                alert(data.responseText);
            }
        });
    }
    sendAjax(0);

Iterate in your readyStateChange method instead of in the for loop. 在您的readyStateChange方法而不是for循环中进行迭代。

    ...
    array_index++;
    var data = selected_elements[array_index];
    if (data) {
        send_ajax_request(data);
    }
}

That is kind of against the whole point of ajax. 这有点与ajax的观点背道而驰。 The first "a" is usually considered to mean "asynchronous", but you want to make the request synchronous (async = false I believe in jQuery) 通常将第一个“ a”表示为“异步”,但是您想使请求同步(async = false,我相信jQuery)

Using recursive call, until previous ajax request not finished, next request cant be processed. 使用递归调用,直到上一个ajax请求未完成,才能处理下一个请求。 So recursive call can solve the problem of these ajax request. 因此递归调用可以解决这些ajax请求的问题。

var queue_element = ["a","b","c","d","e","f","g"];
var execute_queue = function(i){    
  $.ajax( {    
    url: queue_element[i],
    success: function({
    i++;    // going to next queue entry

    // check if it exists
      if (queue_element[i] != undefined){
        execute_queue(i);
      }
    }
  }); // end of $.ajax( {...

}; // end of execute_queue() {...

var index = 0;

execute_queue(index); // go!

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

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