Home >Web Front-end >CSS Tutorial >How Can I Show a Loading Indicator During jQuery AJAX Requests?

How Can I Show a Loading Indicator During jQuery AJAX Requests?

Barbara Streisand
Barbara StreisandOriginal
2024-11-18 01:42:01947browse

How Can I Show a Loading Indicator During jQuery AJAX Requests?

Showing Loading Indication During $.ajax Requests

Question:

How can I display a visual indicator while an asynchronous HTTP request is being made using $.ajax?

Answer:

To indicate that an asynchronous request is being processed, you can utilize loading images. Here are two methods to do so:

Method 1: Inline Display Control

Show the loading image before the request and hide it after the request completes:

$('#loading-image').show();
$.ajax({
  url: uri,
  cache: false,
  success: function(html){
    $('.info').append(html);
  },
  complete: function(){
    $('#loading-image').hide();
  }
});

Method 2: Global Event Binding

Bind the loading image display to global ajaxStart and ajaxStop events. This approach will toggle the image for all ajax requests:

$('#loading-image').bind('ajaxStart', function(){
  $(this).show();
}).bind('ajaxStop', function(){
  $(this).hide();
});

The above is the detailed content of How Can I Show a Loading Indicator During jQuery AJAX Requests?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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