【问题标题】:How to properly fire a callback after an animation and ajax calls have been successfully completed?成功完成动画和 ajax 调用后如何正确触发回调?
【发布时间】:2011-09-29 18:11:11
【问题描述】:

我在为某些内容制作动画时执行了 AJAX 调用。

我想在两者都成功完成后触发回调?

有什么想法吗?

编辑:修正标题中的拼写错误

【问题讨论】:

  • 你能把这两个事件串起来吗? IE。在 AJAX 回调中调用动画,然后将动画回调用于下一个函数?

标签: jquery asynchronous callback


【解决方案1】:

这听起来像是jQuery Deferred 的好候选

这里有一些关于它如何工作的粗略代码。

function doAjax(){
   return $.get('foo.htm'); // or $.ajax, $.getJSON.....etc 
}

function doAnimation(){
   var dfd = $.Deferred();
   $("div").fadeIn(800).delay(1200).fadeOut(300, dfd.resolve);
   return dfd.promise();
}

$.when( doAjax(), doAnimation() )
 .then(function(){
    console.log( 'I fire once BOTH have completed!' );
 })
 .fail(function(){
    console.log( 'I fire if one or more requests failed.' );
 });

一些参考资料:

http://api.jquery.com/promise/

http://www.erichynds.com/jquery/using-deferreds-in-jquery/

根据某些 cmets,我检查以确保动画和 ajax 调用并行执行并且按预期执行,它们确实如此。 http://jsfiddle.net/Gdqfp/4/

【讨论】:

  • 谢谢!智能 jQuerying :)
  • 啊……有点小问题。即使使用.stop 提前停止动画也会触发。我认为我们应该在fadeOut 回调中创建一个新的延迟对象和.resolve。我会尝试编辑您的答案。 编辑:这是一个例子:jsfiddle.net/RwXk2
  • 如果手动停止,动画结果是不是应该标记为fail
【解决方案2】:

这样的事情怎么样,两个成功函数都检查另一个是否已完成使用全局变量?

$.ajax({
  url: 'http://fiddle.jshell.net/favicon.png',
  beforeSend: function( xhr ) {
    window.waitingforajax = true
  },
  success: function( ) {
    window.waitingforajax = false;
    if (window.waitingforanimation) {
      myCallback();
    }   
  }
});

window.waitingforanimation = true;
$('#book').animate({
  opacity: 0.25,
  left: '+=50',
  height: 'toggle'
}, 5000, function() {
  window.waitingforanimation= false;
  if (window.waitingforajax) {
    myCallback();
  }  
});

【讨论】:

  • 是的,这有效,但仅适用于小规模。我可能有多个 AJAX 调用...或多个动画。
【解决方案3】:

你可以使用

jQuery.when( animation, ajax ).then( success );

但这不会同时执行这些方法。另一种选择是:

var stops = 2,
    check = function() {
        if (!--stops) {
            alert('ready!');
        }
    };

$('#elem').animate({opacity:0}, check);
$.ajax('domain.com', check);

编辑:看来我错了。试试 $.when.then 方法,更简洁!

【讨论】:

  • 我不明白。为什么不并行触发它们?
  • @antitoxic 查看我的编辑,我认为 jQuery 实际上确实会使用 when/then 同时触发它们。你的测试结果是什么?
猜你喜欢
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
相关资源
最近更新 更多