【问题标题】:When loading html with ajax in jQuery, how can I make sure my loading gif remains visible the entire time until the html has been added?在 jQuery 中使用 ajax 加载 html 时,如何确保加载 gif 在添加 html 之前始终可见?
【发布时间】:2014-03-14 19:11:38
【问题描述】:

我有一个将一些 HTML 加载到 DOM 中的 ajax 调用。如果调用成功,我会显示一个旋转的加载 gif,当调用完成时,我会隐藏它。代码:

$.ajax({
    url: someUrl,
    type: 'POST',
    dataType: 'json',
    data: someData,
    success: function(response){
        $(myLoadingGif).show(); // Show the loading gif
        $(myContainer).html(response);
    },
    complete: function(){
        $(myLoadingGif).hide(); // Hide the loading gif. Note: HTML has not been added yet
    }
});

问题是:加载 gif 在添加 HTML 之前几秒钟就隐藏了,即使我在 ajax 调用的完整部分中声明了它。我希望它始终可见。而且我不想仅仅为了延迟它而做一个丑陋的 1000 毫秒的 setTimeout() 。我可能会补充一点,加载的 HTML 块相当大。这是一个有 20-40 行的表格。

关于如何确保 gif 在实际添加 HTML 之前保持可见的任何想法?

【问题讨论】:

  • 首先,您不应该在成功时显示加载 GIF,而是在发出请求之前显示。 Complete 将在 Success 后几毫秒调用
  • 你试过把$(myLoadingGif).hide();直接放在$(myContainer).html(response);下面吗?或者您可以检查$(myContainer)元素中的高度或元素数量是否发生变化。
  • 如果数据太多,我怀疑UI的重绘需要太多时间。您可以尝试强制重绘:$(myContainer).hide().html(response).show(0,function(){$(myLoadingGif).hide(100);});

标签: javascript jquery ajax


【解决方案1】:

每次您的 ajax 调用返回值时都会触发成功。当从 Ajax 调用返回最后一个值时,Complete 会触发。因为您的 Ajax 调用只返回一次值,所以成功和完成同时触发。

$(myLoadingGif).show();
$.ajax({
    url: someUrl,
    type: 'POST',
    dataType: 'json',
    data: someData,
    success: function(response){
        // Show the loading gif
        $(myContainer).html(response);
        $(myLoadingGif).hide();
    },
    failure: function(){
        $(myLoadingGif).hide();
    }
    complete:function(){}        
});

试试上面的方法,看看是否可行。

【讨论】:

    【解决方案2】:

    你需要隐藏 gif,在新的 HTML 附加到 DOM 之后,因为 .html() 是同步的,所以在调用 .html() 之后放置的任何代码都将在新的 html 附加到 DOM 后执行。但有时会出现延迟,只是因为添加了 DOM,但浏览器引擎还没有渲染它,它在那里,但没有显示。 为此目的,请尝试 hack,有时它对我很有用:

    $.ajax({
        url: someUrl,
        type: 'POST',
        dataType: 'json',
        data: someData,
        success: function(response){
            $(myLoadingGif).show(); // Show the loading gif
            $(myContainer).html(response);
        },
        complete: function(){
            setTimeout(function(){$(myLoadingGif).hide();},0);
        }
    });
    

    【讨论】:

    • 我的坏你完全正确!我不知道我在想什么,完整的事件在成功执行后启动!
    • 我会尝试一种不同的方法来解决这个问题,一个小同步技巧
    猜你喜欢
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    相关资源
    最近更新 更多