【问题标题】:Is there a way using which I could execute ajax request for n number of times in regular chunk size?有没有一种方法可以让我以常规块大小执行 n 次 ajax 请求?
【发布时间】:2020-04-28 06:16:57
【问题描述】:

下面定义的函数用于创建具有多个动态ajax请求执行的promise对象,

function executeChunkwise(start, end, parameterObj, batchnumber){
    var allPromises = [];

    for(var i=start;i<end;i++) { 
        (function(index){
                allPromises.push(new Promise(function(resolve, reject) {
                    $.ajax({
                        url: "myurl",
                        data: 'queryparameter=' + parameterObj[index],
                        method: 'POST',
                        success: function (response) {
                            $.each(response, function() {
                                idObj = [];
                                $.each(this, function(k, v) {
                                    idObj.push(this.id);
                                });
                                data.push({
                                   'dynamicVar': parameterObj[index],
                                   'products': idObj
                                });
                            });
                        },
                        error: function (response) {
                            resolve(true)
                        }
                    }).done(function(response){
                        resolve(true);
                    });
                }));
        })(i);
    }
    //execute all promised ajax requests and pass the finalised reponse as data to create 
    //the json file via new ajax request.
    Promise.all(allPromises).then((result) => {
        $.ajax({
            url: "jsonGenerator.php",
            data: {
                response: JSON.stringify(data),
                batchnumber: batchnumber
            },
            dataType: 'json',
            cache: false,
            method: 'POST',
            success: function (item) {
                //success
            }
        });
   })
}

在准备好文档时,对于 1000 的块大小,将进一步执行。

$(document).ready(function() {
    val = <?php echo json_encode($records) ?>;
    chunk=1000;
    batchnumber = 1;
    for (start=0,end=val.length; start<end; start+=chunk) {
        var batchend = (start+chunk > end) ? end : start+chunk;
        executeChunkwise(start, batchend, val, batchnumber); 
        batchnumber+=1;
    }
})

结果对于承诺的 ajax 请求很少出现奇怪的错误,

另外,在开发者选项的网络选项卡中,我收到警告消息:

显示临时标题

我不知道我这里执行错了什么,或者执行多个连续的ajax请求有一定的限制。

【问题讨论】:

    标签: php jquery json ajax


    【解决方案1】:

    您的脚本似乎同时触发了数百甚至数千个 ajax 请求。我想这对您的浏览器来说太多了,也许对服务器来说也是如此。 见这里:How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

    尝试通过将它们合并在一起来减少并行 ajax 请求的数量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-17
      • 2023-03-15
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多