开发者

How to display a loading message before the ajax call starts?

$('#wait').ajaxStart(function (){
$(this).css('background-position','0 -90px');
});
var result = $.ajax({
url: "file.php",
async: false,
data: ({id:id}),
type: "post",
cache: false
}).responseText;

The #wait div has a background with an ok, error and wait icons and I want to change the background position of the div BE开发者_如何转开发FORE the ajax call stars, but it's not working. I've tried to alert something from the ajaxStart funcion and it worked, so I don't know from what reason the ajax does not wait for the background position change....


Because your ajax request is synchronous, and javascript is single-threaded, it will block other activities. I'm not sure why your specific case does not work, since I would expect the css method to be completed immediately, but I expect it has to do with the specifics of when a browser actually renders updates the DOM, which may not happen until the thread is completed.

Generally speaking, though, you can avoid this problem entirely by using asynchronous requests. Blocking ajax requests can also create a negative user experience, because the UI is completely disabled while it's taking place. Because of this it's almost always preferable to use an async request. If you need to ensure that page elements are disabled (e.g., effectively simulating a synchronous request), there are plenty of jquery plugins to do this easily. I've had good luck with blockui: http://jquery.malsup.com/block/


Have you tried with the beforeSend(jqXHR, settings) function for the wait background, the error(jqXHR, textStatus, errorThrown) for errors and the success(data, textStatus, jqXHR) function if the request succeeds ?

http://api.jquery.com/jQuery.ajax/


beforeSend(jqXHR, settings)Function

A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings maps are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.


I have the same issue with jQuery mobile trying to display the $.mobile.loading before i send data and in my case it has to go up sync. Some data must be uploaded before others so if if it was all async it may send up some update records before the inserts happen. My solution was to up at setTimeout around the ajax call so that i gave the loading time to show up before ajax fired. Sucky way to do it but until they give me a call back to $.mobile.loading I am stuck using it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜