【问题标题】:Deferred with jQuery - when() with getJSON() callbacks使用 jQuery 延迟 - when() 和 getJSON() 回调
【发布时间】:2013-03-09 11:58:30
【问题描述】:

我正在尝试理解 jQuery 中的 when 函数和延迟对象。

$.when($.getJSON('/echo/json', function () {
    console.log('sucess');
}, function () {
    console.log('error');
})).then(console.log('get JSON ready!'));

这个例子返回:

get JSON ready!
sucess

...但我想先触发成功回调:

sucess
get JSON ready!

我该怎么做?

http://jsfiddle.net/lukaszr/rBFmL/

【问题讨论】:

    标签: javascript jquery jquery-deferred deferred


    【解决方案1】:

    您忘记了函数包装器 - 您的代码立即调用 console.log 而不是传递回调函数:

    .then(console.log('get JSON ready!'));
    

    应该是:

    .then(function() {
        console.log('get JSON ready!');
    });
    

    Fiddle

    【讨论】:

      【解决方案2】:

      尝试使用 .done(...) 而不是 .then(...)。 jQuery 文档中有示例。

      http://api.jquery.com/jQuery.when/

      【讨论】:

        猜你喜欢
        • 2012-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多