单击按钮,我正在运行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秒,如果是,则运行回调。关于在这里做什么的任何想法?我基本上想避免在动画完成之前加载数据的情况。
答案 0 :(得分:2)
所以这是交易。您将在启动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); };
}
}
});
}
答案 1 :(得分:1)
这是我的解决方案:
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.
}
答案 2 :(得分:0)
您可以简单地编写一个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);
}
});
}