简体   繁体   中英

AJAX calls inside a loop

So, I have a list of data that I am out putting onto my view, and each list item has an id.

Each of these list items is a bar and I have a document created for each bar that at least one user is going to. For those bars where no users are going, there is no document created.

I need to make an AJAX call for each list item to the database to check

i) If a document exists for that list item ii) If a document exists, how many users are going according to the document.

I attempted a solution using a while loop, where the update for the while loop was contained in the callback for the AJAX call. Here is the code

function updateAllGoingButtons(){
    var i = 0;
    var dataToPass = {};
    var numButtons = global_data_object.listData.businesses.length;
    while(i < numButtons){
        dataToPass.button = global_data_object.listData.businesses[i].id;
        dataToPass = JSON.stringify(dataToPass);
        ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', '/update-buttons', dataToPass, function(data){
            console.log(i);
            i++;
        }));
    }
}

When I attempted to run the function, I got the error,

Request entity too large

So, is there a better way to go about doing what I am trying to do? Should I use promises? Or is there simply an error in the way I am trying to make the AJAX call from within a while loop?

For reference, here is the ajaxRequest function

'use strict';

var appUrl = window.location.origin;
var ajaxFunctions = {
   ready: function ready (fn) {
      if (typeof fn !== 'function') {
         return;
      }

      if (document.readyState === 'complete') {
         return fn();
      }

      document.addEventListener('DOMContentLoaded', fn, false);
   },
   ajaxRequest: function ajaxRequest (method, url, data, callback) {
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            callback(xmlhttp.response);
         }
      };

      xmlhttp.open(method, url, true);
      xmlhttp.setRequestHeader('Content-type', 'application/json');
      xmlhttp.send(data);
   }
};

You should check out the npm library called async, it has an each method that you can do asynchronous calls within. If you use promises, the Promise.all method in Bluebird could be very useful for you.

So, here's how I did the multiple AJAX calls from within a loop. I used this resource https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.d7ymg99mp (Great resource!)

Here's the code

$('.btn-group').find('button').each(function() {
        console.log($(this).attr('id'));
        dataToPass.button = $(this).attr('id');
        var ajax = $.ajax({
            url: '/update-buttons',
            method: 'post',
            data: dataToPass,
            dataType: 'json',
        }).success(function(data){
            console.log(data);
        });
    });

Essentially, what this does is selects a div with the class 'btn-group' and then iterates over each button within that div using the jQuery each operator. Then simply make an AJAX request and use the success chain callback to access the returned data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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