简体   繁体   中英

Ajax loading spinner

How can I add loading spinner (some gif) for each image while loading and when image is loaded I want to remove spinner. Here is my code:

$.ajax({
  url: 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
  cache: false,
  dataType: 'json',
  data: {
    tags    : 'cats',
    format  : "json"
  }
}).done(function( responseData ){
  html = '<row>';
  $.each( responseData.items, function( index, cat ){
    html += '<div class="col-md-3">';
    html += '<a href="' + cat.link +'" class="thumbnail">';
    html += '<img src="' + cat.media.m + '" alt="" class="images">';
    tml += '</a></div>';
  }); // end $.each
  html += '</row>';
  $('#photos').html(html);
  $searchField.attr('disabled', false);
  $submitButton.attr('disabled', false).text('Search');
});

Thanks,

use beforeSend and complete option at Ajax

$.ajax({
    url: 'https://api.flickr.com/services/feeds/photos_public.gne?      jsoncallback=?',
   cache: false,
   dataType: 'json',
   data: {
      tags    : 'cats',
      format  : "json"
   },
   beforeSend: {
      // add loading spinner
   },
   complete: {
      // remove loading spinner
   }
   }).done(function( responseData ){
      html = '<row>';
      $.each( responseData.items, function( index, cat ){
         html += '<div class="col-md-3">';
         html += '<a href="' + cat.link +'" class="thumbnail">';
         html += '<img src="' + cat.media.m + '" alt="" class="images">';
         tml += '</a></div>';
      }); // end $.each
      html += '</row>';
      $('#photos').html(html);
      $searchField.attr('disabled', false);
      $submitButton.attr('disabled', false).text('Search');
   });

You can do somthing like this:

...
html += '<img src="' + cat.media.m + '" alt="" class="images hidden">';
html += '<span class="spinner"></span>';
...


$("#photos img").load(function() {
    $(this).show();
    $(this).siblings('.spinner').remove();
});

The hidden class in the img tag hides your image using css:

.hidden {
    display: none;
}

It's up to you how you'll add the spinner in the <span class="spinner"></span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM