Home > Web Front-end > CSS Tutorial > How Can I Display a Loading Image During Asynchronous AJAX Requests?

How Can I Display a Loading Image During Asynchronous AJAX Requests?

Linda Hamilton
Release: 2024-11-24 03:36:14
Original
818 people have browsed it

How Can I Display a Loading Image During Asynchronous AJAX Requests?

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();
  }
});
Copy after login

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();
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template