循环内的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个回答


您应该检出名为async的npm库,它具有您可以在其中执行异步调用的each方法。 如果您使用诺言,那么Bluebird中的Promise.all方法可能对您非常有用。</ p>
     </ div>

展开原文

原文

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.


所以,这就是我从一个循环中进行多个AJAX调用的方式。 我使用了此资源 https://medium.com/coding-design/ Writing-better-ajax-8ee4a7fb95f#.d7ymg99mp (很棒的资源!)</ p>

这是代码</ p>

  $('。btn-group')。find('button')。each(function(){
         console.log($(this).attr('id'));
         dataToPass.button = $(this).attr('id');
         var ajax = $ .ajax({
             网址:“ / update-buttons”,
             方法:“发布”,
             数据:dataToPass,
             dataType:'json',
         })。success(函数(数据){
             console.log(data);
         });
     });
</ code> </ pre>

从本质上讲,它的作用是选择一个带有“ btn-group”类的div,然后使用jQuery每个运算符遍历该div中的每个按钮。 然后只需提出AJAX请求,并使用成功链回调来访问返回的数据。</ p>
     </ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐