如何在Ajax请求处理期间显示动画图标 - Rails 3

SHU*_*ake 11 ruby ajax jquery ruby-on-rails ruby-on-rails-3

我正在尝试为每个ajax请求显示加载指示器,我在rails 3应用程序中工作.

HTML:

<div id="loading-indicator">
 <%= image_tag("loading.gif", :id => "loading-indicator", :style => "display:none") %>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

#loading-indicator {
   position: absolute;
   left: 10px;
   top: 10px;
 }
Run Code Online (Sandbox Code Playgroud)

loading.js :我放在assest/javascripts /中

$(document).ready(function(){
    $(document).ajaxSend(function(event, request, settings) {
        $('#loading-indicator').show();
    });

    $(document).ajaxComplete(function(event, request, settings) {
        $('#loading-indicator').hide();
    });
});
Run Code Online (Sandbox Code Playgroud)

我的application.js看起来像这样:

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
Run Code Online (Sandbox Code Playgroud)

它起作用,没有任何表现.任何帮助,将不胜感激.

Mur*_*foX 16

我通常会将这段代码保存到以下情况中:

$(function() {
  $('#loading-indicator')
    .hide()  // hide it initially.
    .ajaxStart(function() {
      $(this).show(); // show on any Ajax event.
    })
    .ajaxStop(function() {
      $(this).hide(); // hide it when it is done.
  });
});
Run Code Online (Sandbox Code Playgroud)

---编辑---

这不适用于最新版本的jQuery.从jQuery 1.8开始,该.ajaxStart()方法应该只附加到document.因此代码应如下所示:

$(function() {
  $('#loading-indicator').hide();  // hide it initially.
  $(document)  
    .ajaxStart(function() {
      $('#loading-indicator').show(); // show on any Ajax event.
    })
    .ajaxStop(function() {
      $('#loading-indicator').hide(); // hide it when it is done.
  });
});
Run Code Online (Sandbox Code Playgroud)