【问题标题】:Display loading GIF image while loading with AJAX使用 AJAX 加载时显示加载 GIF 图像
【发布时间】:2012-06-05 00:40:02
【问题描述】:
   $.ajax({
        url: "/image/productImages.jpg",
        timeout:5000,

        beforeSend: function(){
    // Handle the beforeSend event
        $('##loading').show();
        },

        complete: function(){
        // Handle the complete event
        $('##loading').hide();
        },

        success: function (data) {
            alert("image was added successfully");
        },

        error: function () {
            alert("There was an error. Image could not be added, please try again");
        }
    });

我想在加载图像时显示显示加载 gif,然后在加载图像后将其删除。在这里,我有这段代码可以做到这一点,但是,这会直接出错。有谁知道为什么或如何解决这个问题。提前致谢!

【问题讨论】:

  • 致所有投票结束或发布## 错误的人。阅读问题,他正在访问错误处理程序。 ## 是您在冷融合中逃避 # 的方式,因为冷融合变量包含在 # 中。
  • 当然,我在这里做了一个很大的假设,因为 ## 是代码/问题中唯一引用 CF 的东西。绝对不应该排除它。
  • 凯文是正确的。我在这个周围有 CF 标记...抱歉造成混淆。

标签: jquery ajax loading


【解决方案1】:

所以我发现您无法在 .ajax 标记中将图像加载为 url。感谢您的回复,但##loading 仅适用于冷融合标签

.load() 建议如下:

 var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
                  .load(function() {
                     if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                         alert('broken image!');
                     } else {
                         $("#something").append(img);
                     }
          });

但是,这也破坏了我已经实现的代码,并且在 IE 中不起作用......很遗憾。

【讨论】:

    【解决方案2】:

    如果您要访问错误处理程序,则错误将与服务器返回的数据有关。尝试将此作为错误处理程序以获取有关正在发生的事情的更多信息(在浏览器的控制台中查看结果):

    error: function (x,y,z) {
        alert("There was an error. Image could not be added, please try again");
        console.log(x,y,z);
        //alert(x + "\n" + y + "\n" + z);
    }
    

    不过,有一种更简单的方法可以预加载图片。试试这个:

    $("#loading").show();
    var img = new Image();
    $(img).load(function(){
        $("#loading").hide();
    });
    img.src = "/image/productImages.jpg";
    

    【讨论】:

    • 另外观察控制台中的请求/响应,这可能会很快指出一些错误。
    【解决方案3】:

    您的 id 选择器有两个哈希,

    试试这个:

     $('#loading').show();
    

    【讨论】:

    • 哦,那只是因为它是围绕冷聚变说唱的...需要##
    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多