当加载html与ajax在jQuery,我怎么能确保我的加载gif保持可见的整个时间,直到html已添加

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?

本文关键字:html 加载 时间 添加 直到 我的 jQuery ajax 怎么能 gif 确保      更新时间:2023-09-26

我有一个ajax调用,它将一些HTML加载到DOM中。如果调用成功,我显示一个旋转加载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
    }
});

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

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

每次ajax调用返回值时都会触发Success。当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(){}        
});

在新的HTML附加到DOM之后,您需要隐藏gif,因此因为. 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);
    }
});