【问题标题】:JQuery two different asynchronous ajax call returns undefinedJQuery 两种不同的异步 ajax 调用返回 undefined
【发布时间】:2017-08-04 12:23:51
【问题描述】:

我已经检查了有关此问题的所有类似问题,但仍然无法弄清楚它应该如何工作。谁能带领我朝着正确的方向前进。 data 和 data2 没有按时加载,但是在我跳过 $.when 部分后它们出现在 chrome 调试器中。提前致谢。

function First (number) {    
  return $.ajax({
        url: "/…",
        data: { 'number': number },
        type: "POST",
        cache: "False",
        success: function (data) {
            return data;
        },
        error: function (xhr, type) {
            alert('Something went wrong.')
        }
    });
}

function Second (number) {    
  return $.ajax({
        url: "/…",
        data: { 'number': number },
        type: "POST",
        cache: "False",
        success: function (data2) {
            return data2;
        },
        error: function (xhr, type) {
            alert('Something went wrong.')
        }
    });
}

function DoSomeBusiness(number) {
    $.when(First(number), Second(number)).then(function (data, data2) {
       var someData = data; // data and data2 is undefined for sometime but right after I pass this line of code they appear correctly but i cannot use them cause they’re not loading on time.
       var someData2 = data2;          
    });    

    .. do some business           
};

【问题讨论】:

标签: jquery ajax asynchronous jquery-deferred


【解决方案1】:

不要在 ajax 调用中使用成功/错误字段,你应该在 .then 回调中管理它们

编辑: 并且缓存字段应该是一个布尔值

编辑2: 这个问题不是很清楚,我认为问题是那些干扰延迟行为的回调之一,因为代码看起来很好。 也许OP想要访问他写的数据和data2

 .. do some business     

这是一个错误,因为任何内容都会在 .then 回调中的任何内容之前执行。 所以 OP 只需将您的代码移动到回调中,它应该可以工作

【讨论】:

  • 在第一行展开... return in success 什么都不做,也不是承诺链的一部分
猜你喜欢
  • 2011-06-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 2013-05-23
  • 2017-06-29
相关资源
最近更新 更多