单击按钮时,我正在运行ajax请求。我还更改了 body 类以执行 css 动画(为 ajax 数据腾出空间),大约需要 1.5 秒。我不希望 ajax 在此时间之前返回数据。
我的 ajax 请求如下所示:
function ajax(url) {
$.ajax({
url: API.hostname + url,
dataType: "json",
complete: function() {
$html.css("cursor", "default");
},
success: function (response) {
callback(response);
}
});
}
理想情况下,我运行一个计时器,并检查它是否是完整的 1.5 秒,如果是,则运行回调。对在这里做什么有什么想法吗?我基本上想避免在动画完成之前加载数据的情况。
所以这是交易。您将在启动 ajax 的同时启动动画,并且在动画完成之前不触发回调。所以。。。
|--------------------------------|
animation starts animation completes
|---------------|----------------|
ajax starts ajax completes callback fires
或
|--------------------------------|
animation starts animation completes
|------------------------------------------|
ajax starts ajax completes / callback fires
因此,如果 Ajax 在动画完成之前返回,它会等待动画,如果 Ajax 在动画之后出现,它将立即触发。在某种程度上,这是两全其美的,因为动画始终受到尊重,用户不必等待惰性的ajax请求(动画之后发生的请求)。
function ajax(url) {
// init cb to null
var cb = null;
// start the 1.5 second long animation
animationStart();
// set timeout for 1.5 seconds
setTimeout(function(){
// cb will be set to a function if the ajax has completed already
if(cb){
// ajax has already completed
cb(); // run the function set by ajax success
}else{
// ajax has not yet completed
cb = true; // set value to true
}
}, 1500);
// start the ajax request
$.ajax({
url: API.hostname + url,
dataType: "json",
complete: function() {
$html.css("cursor", "default");
},
success: function (response) {
// the cb will be set by the timeout if the animation is complete already
if(cb){
// animation was already complete, fire the callback right away
callback(response);
}else{
// animation is not yet complete, set cb to a function, so the callback can
// run it when the animation is complete
cb = function(){ callback(response); };
}
}
});
}
的解决方案:
function startanim(){
//here is the script for starting the animation
}
function stopanim(){
//here is the script for stopping the animation
}
function ajax(url) {
startanim();//start your animation before the ajax call
//set a timeout if you want to set the minimum time for animation
setTimeout(function (){
$.ajax({
url: API.hostname + url,
dataType: "json",
complete: function() {
$html.css("cursor", "default");
},
success: function (response) {
callback(response);
},
error : function (a){
alert(a.responseText); //trap the cause of error
}
}).done(function (){
stopanim();//stop your animation after the ajax done
});
},"1400",url);
//timeout is 1400ms. Let's say that the ajax needs 100ms to complete, so it will be 1500ms.
}
您可以简单地编写一个 ajax done 方法,该方法仅在发出请求后触发。
来自jQuery网站的官方文档:http://api.jquery.com/ajaxcomplete/
function ajax(url) {
$.ajax({
url: API.hostname + url,
dataType: "json",
complete: function() {
$html.css("cursor", "default");
}.done(function(event){
do something cool
}),
success: function (response) {
callback(response);
}
});
}