【问题标题】:Loader-GIF doesn't move when AJAX is loading加载 AJAX 时 Loader-GIF 不移动
【发布时间】:2017-03-24 09:47:21
【问题描述】:

我正在尝试制作一个 GIF 加载器,只要我的 AJAX 请求正在处理,它就会显示出来。我正在使用jquery loader plugin。

问题是,当浏览器忙于处理 AJAX 请求时,GIF 不会移动,但在将其设置为 visible 以进行测试时它会移动。
我已经在 3 个主流浏览器中测试过了。

这是我的代码的摘录。当然,真正的代码要复杂得多:

  $("#myButton").click(function() {
    $.loader({
      className: "blue-with-image-2",
      content: ''
    });

    getData();
  });

  function getData() {
    $.ajax({
      type: "GET",
      url: "https://jsonplaceholder.typicode.com/photos",

      success: function(data) {
        // do something with data
        console.log(data)
        $.loader('close'); // close the loader
      },
      error: function(jqXHR, status, error) {
        console.error(status, error);
      }
    });
  }

Here is a fiddle with that example code.

有趣的是,在 jsFiddle 中测试这段特定代码时,确实如此 工作。但不是我的真实代码,它几乎相同,只是更复杂。

【问题讨论】:

  • 您描述的症状听起来像是请求正在同步发出并阻止 UI 更新。您是否在全局 AJAX 设置中设置了 async: false?
  • @RoryMcCrossan:不,我唯一停用的是缓存。

标签: javascript jquery ajax jquery-ui animated-gif


【解决方案1】:

在ajax调用中使用函数'beforeSend'

function getData() {
$.ajax({
  type: "GET",
  url: "https://jsonplaceholder.typicode.com/photos",
  beforeSend: function() {
      $('#response').html("<img src='/images/loading.gif' />");
  },
  success: function(data) {
    // do something with data
    console.log(data)
    $.loader('close'); // close the loader
  },
  error: function(jqXHR, status, error) {
    console.error(status, error);
  }
});

【讨论】:

  • 谢谢,可惜没有解决问题。
猜你喜欢
  • 2014-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
  • 2011-08-15
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
相关资源
最近更新 更多