簡體   English   中英

AJAX在循環內調用

[英]AJAX calls inside a loop

所以,我有一個數據列表,我將其放在我的視圖中,每個列表項都有一個id。

這些列表項中的每一個都是一個條形圖,我為至少一個用戶要訪問的每個條形圖創建了一個文檔。 對於那些沒有用戶去的酒吧,沒有創建文檔。

我需要對數據庫的每個列表項進行AJAX調用以進行檢查

i)如果該列表項存在文檔ii)如果存在文檔,則根據該文檔有多少用戶。

我嘗試使用while循環的解決方案,其中while循環的更新包含在AJAX調用的回調中。 這是代碼

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++;
        }));
    }
}

當我試圖運行該函數時,我收到了錯誤,

請求的實體太大

那么,有沒有更好的方法來做我想做的事情? 我應該使用承諾嗎? 或者,我試圖在while循環中進行AJAX調用的方式只是一個錯誤?

作為參考,這里是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);
   }
};

你應該看看名為async的npm庫,它有一個你可以在其中進行異步調用的方法。 如果你使用promises,Bluebird中的Promise.all方法可能對你非常有用。

所以,這是我如何在循環中進行多個AJAX調用。 我使用了這個資源https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.d7ymg99mp (很棒的資源!)

這是代碼

$('.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);
        });
    });

本質上,它的作用是選擇一個帶有'btn-group'類的div,然后使用jQuery each運算符迭代該div中的每個按鈕。 然后只需發出一個AJAX請求並使用成功鏈回調來訪問返回的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM