I want to give a spinning gif image for the user to know something开发者_如何学JAVA is happening while I am doing an ajax call with jquery. I have to use async:false because otherwise the code gets confused and we end up with a bad session variable. Here is what I have (that does not show the gif until after the call has frozen the screen.)
$('#status' + itemNum).html("<img width='14px' src='/style/images/spinner.gif'>");
if (foo == "bar") {
$.ajax({
type:"POST",
url: "foobar.html",
async:false,
data: "val1=" + escape(newValue) + "&val2=" + fieldName + "&val3=" + newValue2
})
} else {
$.ajax({
type:"POST",
url: "foobar.html",
data: "val1=" + escape(newValue) + "&val2=" + fieldName + "&val3=" + newValue3
})
document.getElementById('status' + itemNum).innerHTML = "SAVED";
}
$("#status" + itemNum).show();
setTimeout("fade_out('"+itemNum+"')", 1000);
}
In this case I only want the async when foo = bar. Can anyone let me know why the spinner.gif loads after the call. I am thinking that might be because the spinner isn't anywhere else and there is a delay in loading it, but still it doesn't show up when called multiple times (should be in cache by then), so I'm stumped.
Thanks!
This is not possible.
Since Javascript runs in the UI thread, async: false
will freeze the browserm including all animation.
Do not use async: false
!
You need to fix your code to handle asynchronous requests.
async: false
will lock the browser, resulting in all animations being paused until processing is allowed to continue. You can however get the graphic to at least show up before the ajax calls by placing the ajax calls inside of a setTimeout
with a delay of 1ms or greater. It still will not animate though, even though it is an animated gif.
Of course, the above is just a bandaid, the better solution would be to not use async: false
.
精彩评论