"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Display a Loading Image During Asynchronous AJAX Requests?

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

Published on 2024-11-19
Browse:798

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3