简体   繁体   English

AJAX在循环内调用

[英]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. 所以,我有一个数据列表,我将其放在我的视图中,每个列表项都有一个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 我需要对数据库的每个列表项进行AJAX调用以进行检查

i) If a document exists for that list item ii) If a document exists, how many users are going according to the document. i)如果该列表项存在文档ii)如果存在文档,则根据该文档有多少用户。

I attempted a solution using a while loop, where the update for the while loop was contained in the callback for the AJAX call. 我尝试使用while循环的解决方案,其中while循环的更新包含在AJAX调用的回调中。 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? 或者,我试图在while循环中进行AJAX调用的方式只是一个错误?

For reference, here is the ajaxRequest function 作为参考,这里是ajaxRequest函数

'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. 你应该看看名为async的npm库,它有一个你可以在其中进行异步调用的方法。 If you use promises, the Promise.all method in Bluebird could be very useful for you. 如果你使用promises,Bluebird中的Promise.all方法可能对你非常有用。

So, here's how I did the multiple AJAX calls from within a loop. 所以,这是我如何在循环中进行多个AJAX调用。 I used this resource https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.d7ymg99mp (Great resource!) 我使用了这个资源https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.d7ymg99mp (很棒的资源!)

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. 本质上,它的作用是选择一个带有'btn-group'类的div,然后使用jQuery each运算符迭代该div中的每个按钮。 Then simply make an AJAX request and use the success chain callback to access the returned data. 然后只需发出一个AJAX请求并使用成功链回调来访问返回的数据。

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

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