等待AJAX请求响应

Waiting for AJAX request response

本文关键字:响应 请求 AJAX 等待      更新时间:2023-09-26

我有以下函数,在ABC.PrintReport.reportData中存储一些数据。我使用AJAX请求获取数据。然后,我想在getKeyData函数结束时打开的新窗口中打印数据。

但是,当窗口打开时,AJAX请求还没有返回数据,所以我得到了关于未定义属性的错误。这个的解是什么?

getKeyData: function () {
    for (var key in ABC.PrintReport.keyList) {
        k = ABC.PrintReport.keyList[key].Report_Key;
        ABC.PrintReport.reportData[k] = null;
        (function(index) {
            Ext.Ajax.request({
                url: ABC.Core.servicePath + '/task/' + ABC.PrintReport.processInstanceID + '/report/' + ABC.PrintReport.keyList[key].Report_Key + '?portalID=' + ABC.Core.portalID,
                success: function (response) {
                    ABC.PrintReport.reportData[index] = Ext.JSON.decode(response.responseText)[0];
                }
            });
        })(k);
    }
    window.open(location.pathname + 'resources/printreport.html');
},

如何使用不同的对象和承诺?虽然我没有看到一个方法all(),应该帮助你解决你的问题,如下所示。

我建议使用Q库,参见组合部分。

all函数返回一个值数组的promise。当这个promise被实现时,数组将包含原始promise的兑现值,按照与这些promise相同的顺序。

那么你做:

Q.allSettled(promises)
.then(function (results) {
    window.open(location.pathName + 'recources/printreport.html');
});

这比使用已成功请求的计数器更干净。

尽管正在进行的请求数量是可变的,但您可以跟踪它们,并在最后一个请求完成时在success方法中打开窗口。

getKeyData: function () {
    var total = ABC.PrintReport.keyList.length;
    var loaded = 0;
    for (var key in ABC.PrintReport.keyList) {
        k = ABC.PrintReport.keyList[key].Report_Key;
        ABC.PrintReport.reportData[k] = null;
        (function(index) {
            Ext.Ajax.request({
                url: ABC.Core.servicePath + '/task/' + ABC.PrintReport.processInstanceID + '/report/' + ABC.PrintReport.keyList[key].Report_Key + '?portalID=' + ABC.Core.portalID,
                success: function (response) {
                    ABC.PrintReport.reportData[index] = Ext.JSON.decode(response.responseText)[0];
                    loaded++;
                    if (loaded == total) {
                        window.open(location.pathname + 'resources/printreport.html');
                    }
                }
            });
        })(k);
    }
},

或者您可以使用async lib,创建一个并行ajax调用,然后在所有ajax请求完成时使用window.open调用您的回调。