Displaying Loading Image during Asynchronous Requests
Performing asynchronous requests using $.ajax can lead to confusion due to the lack of visible indication of the ongoing process. This article explores techniques to show a loading image during such requests.
To begin with, the provided code snippet performs an asynchronous request to a URL and appends the received HTML to an element with the class 'info'. To display a loading image, an image element with an 'id' of 'loading-image' can be used.
One approach is to show the image before making the request and hide it after completion:
$('#loading-image').show(); $.ajax({ url: uri, cache: false, success: function(html){ $('.info').append(html); } complete: function(){ $('#loading-image').hide(); } });
A more general approach is to bind the loading image to the global ajaxStart and ajaxStop events. In this way, the image will be visible for all asynchronous requests:
$('#loading-image').bind('ajaxStart', function(){ $(this).show(); }).bind('ajaxStop', function(){ $(this).hide(); });
These techniques provide a user-friendly indication of the ongoing asynchronous request, enhancing the user experience.
The above is the detailed content of How Can I Display a Loading Image During Asynchronous AJAX Requests?. For more information, please follow other related articles on the PHP Chinese website!