Jquery中的延迟Ajax
我有一个简单的页面,通过点击按钮,通过ajax函数将新数据加载到DIV。 当用户单击另一个按钮时,该DIV消失,数据加载,DIV再次消失。问题在于,当用户单击按钮DIV时,该按钮会逐渐消失,但新数据已经加载 我试着使用callbackinfadeout函数来防止在淡出之前加载新数据,但没有帮助。我的代码如下: 使用回调淡出的影响: 加载页面功能:Jquery中的延迟Ajax,jquery,ajax,delay,wait,fadeout,Jquery,Ajax,Delay,Wait,Fadeout,我有一个简单的页面,通过点击按钮,通过ajax函数将新数据加载到DIV。 当用户单击另一个按钮时,该DIV消失,数据加载,DIV再次消失。问题在于,当用户单击按钮DIV时,该按钮会逐渐消失,但新数据已经加载 我试着使用callbackinfadeout函数来防止在淡出之前加载新数据,但没有帮助。我的代码如下: 使用回调淡出的影响: 加载页面功能: loadPage: function(bottomMenu) { $("#indicator").show();
loadPage: function(bottomMenu) {
$("#indicator").show();
$.ajax({url: bottomMenu.attr('href'),
dataType: 'html',
timeout: 5000, // 5 seconds
success: function(html) {
$("#indicator").hide();
$("#core").html(html).fadeIn(500);
}
}
我做错了什么?为什么淡出不等待500毫秒,然后运行loadpage功能。为什么会直接触发Ajax功能?试试:
$("#core").fadeOut(500, function(){
processingPages.loadPage(clickedButton);
});
这是一个常见的错误。您的意思是传递函数,但实际上您传递的是函数的返回值,因为您是立即执行的,而不是请求它在以后执行
在我的例子中,我传递的是一个匿名函数(不是函数的返回值),当执行该函数时(即淡出后),它不会影响代码
这是函数引用和函数调用之间的区别
alert //reference to alert function
alert('hello'); //invocation of alert function
使用承诺。让事情变得非常简单
var fadingOut = $("#core").fadeOut(500).promise()
fadingOut.done(function() {
processingPages.loadPage(clickedButton)
});
虽然这是一个简单的例子,但养成这个习惯,一切都会变得容易得多
您甚至可以在ajax中使用承诺,默认情况下,jQueryAjax调用返回承诺。
您的loadPage函数可能如下所示:
loadPage: function(bottomMenu) {
$("#indicator").show();
var gettingData = $.ajax({url: bottomMenu.attr('href'),
dataType: 'html',
timeout: 5000
});
gettingData.done(function(html) {
$("#indicator").hide();
$("#core").html(html).fadeIn(500);
});
gettingData.fail(function() {alert("There was a problem loading your data";});
}
var fadingOut = $("#core").fadeOut(500).promise()
fadingOut.done(function() {
processingPages.loadPage(clickedButton)
});
loadPage: function(bottomMenu) {
$("#indicator").show();
var gettingData = $.ajax({url: bottomMenu.attr('href'),
dataType: 'html',
timeout: 5000
});
gettingData.done(function(html) {
$("#indicator").hide();
$("#core").html(html).fadeIn(500);
});
gettingData.fail(function() {alert("There was a problem loading your data";});
}