【问题标题】:Waiting for AJAX request response等待 AJAX 请求响应
【发布时间】:2014-04-24 08:45:51
【问题描述】:

我有以下函数将一些数据存储在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');
},

【问题讨论】:

  • 为什么不在你的 Ajax 请求的 success 函数中打开它?
  • 在你的成功函数中打开窗口
  • 有多个ajax请求。可以是 3 到 6 之间的任何值。请求处于 for 循环中。

标签: javascript ajax


【解决方案1】:

使用deffered objects and promises 怎么样?虽然我没有看到可以帮助您解决问题的方法 all(),如 here 所示。

我建议使用Q library,请参阅组合部分。

all 函数返回一个值数组的承诺。当这个 Promise 被实现时,该数组包含原始 Promise 的实现值,与这些 Promise 的顺序相同。

然后你做:

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

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

【讨论】:

    【解决方案2】:

    即使正在进行的请求数量不定,您也可以跟踪它们并在最后一个请求完成时以成功方法打开窗口。

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多