weixin_33734785 2016-10-17 05:10 采纳率: 0%
浏览 46

循环内的AJAX调用

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);
   }
};
  • 写回答

2条回答 默认 最新

  • weixin_33722405 2016-10-17 05:22
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题