How can I make batches of ajax requests in jQuery?

前端 未结 4 2051
半阙折子戏
半阙折子戏 2020-12-05 05:35

I\'m wondering how to make ajax calls in groups of n.

Here\'s my use case:

I have a table that displays usage data. You can drill into each row, and if eac

4条回答
  •  死守一世寂寞
    2020-12-05 06:02

    Ajax calls using jQuery are typically asynchronous. So, if you have 50 rows, jQuery will asynchronously send all 50 requests--you don't get to control the sequence of processing when you get responses from the server.

    You can use async: false on the $.ajax call such that only one request is sent to the server as you loop through your rows:

    $.ajax({
        url: location,
        data: params,
        async: false,
        success: function(msg) { // do something}
    });
    

    The issue with this approach (async: false) is that user may experience a "freeze" or unresponsive page.

    Another way is to use recursion in your JavaScript so that the calls are still asynchronous but the ajax call still waits for the success event of each row like the following:

    var maxRows = 50;
    
    function myFunc(index) {
       $.ajax({
           url: location,
           data: params,
           async: true,
           success: function(msg) { 
                if (index < maxRows) {
                   // do something
                }
                else {
                   return; //index equals maxRows--stop the recursion
                }
                index++;
                myFunc(index); //call the function again
           }
       });
    
       $(document).ready(function() {
           myFunc(0);      
       });
    }
    

提交回复
热议问题