使用$ .ajax加载图片

时间:2012-10-19 02:40:28

标签: jquery

我试过this answer

这是我的功能,当我点击图片时我会调用它。

function CheckOut(urlCheckoutNew,urlWebService) {
  var inputData = JSON.stringify(getQuotation(urlCheckoutNew));
  $('#imgloading').show();
  $.ajax({
    type: 'POST',
    url: urlWebService,
    contentType: 'application/json',
    processData: false,
    dataType: 'json',
    data: inputData,
    success: function (dataQuote) {
        //alert(1);
        $('#imgloading').hide();
    }
  });
}

这是我的HTML:

<div id="imgloading" style="display:none;">
    <img src="/Content/Images/ImageModal/loading.gif" alt="Confirming"/>
</div>

该功能处于状态success警报正在运行,但图像未加载。 弹出警告对话框时,我看到加载图像正在后台加载。但是当我评论警报时,图像没有显示出来。

有谁能告诉我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

图像毫无疑问正在加载,它只是再次隐藏得如此之快,以至于它永远不会完全可见。

像这样测试:

$.ajax({
    type: 'POST',
    url: urlWebService,
    contentType: 'application/json',
    processData: false,
    dataType: 'json',
    data: inputData,
    success: function (dataQuote) {
        $('#imgloading').fadeOut(2000);
    }
});

结果应该是您的图像出现然后慢慢淡出。这可能不是您的预期行为,但它会确认您的图像确实正在加载(因为alert()方法无法令人信服......)。

您可能希望在短时间内显示图像,以便为用户提供确实发生某些事情的安全感。在这种情况下,我建议推迟隐藏图像。有很多方法可以实现这一目标,但我通常会执行以下操作:

success: function (dataQuote) {
    var $image = $('#imgloading')
    $image.show(500, $image.fadeOut(2000));
}

由于图像已经显示,show()是多余的,并且只是一个简单的延迟。

答案 1 :(得分:1)

$('#imgloading').html('');

它将删除#imgloading的html,以便图像消失

并且您没有显示图像

<div id="imgloading" style="display:none;">
                              ^^^^^^^^^^^-------its hidden already 

    <img src="/Content/Images/ImageModal/loading.gif" alt="Confirming"/>
</div>

答案 2 :(得分:1)

查看代码,首先显示图像:

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

然后执行AJAX请求,并在成功时隐藏它:

$('#imgloading').hide();

如果图像看起来根本没有显示,可能会出现一些&#34;问题&#34;:

  1. 请求是同步的,因此页面没有机会在两者之间进行更新。

  2. 请求速度太快,图片只显示很短的时间;您可以将hide()包裹在setTimeout()内以延迟隐藏并验证其是否正常工作,尽管您已经使用alert()证明了这一点。

    < / LI>
  3. 与上一个相关,当您显示<div>时,浏览器会先加载图片;取决于需要多长时间,当您的请求返回时,它将再次被隐藏。