【问题标题】:jQuery: Call function after ajax has completely renderedjQuery:ajax完全呈现后调用函数
【发布时间】:2023-03-11 21:30:02
【问题描述】:

我正在使用函数pinterest_it() 来调整带有masonry.js 的视图,并且我正在使用另一个函数recipeLoader() 来显示加载图标,直到页面完全加载,然后显示内容。这适用于页面刷新,但是当我使用 ajax 加载内容时,我的 $( window ).load(...) 函数永远不会触发。

如何在所有内容完全加载(不是.ready)后进行函数调用

function pinterest_it() {
    $(".loader").show(); # shows loading icon
    $("#recipe-index").css("opacity", 0); # makes content invisible

    if ( $(document).innerWidth() < 991 ) {
        gutter = 0
    } else {
        gutter = 16
    }

    var $grid = $('.grid').imagesLoaded( function() {

        var $blah = $('.grid').masonry({
            itemSelector: '.grid-item',
            columnWidth: function( containerWidth ) {
                return $('.grid-sizer').width();
            },
            percentPosition: true,
            gutterWidth: gutter
        });

    }, fixGrid())

    recipeLoader(); # see below
}

function recipeLoader() {
    console.log("recipe loader")
    $(window).load(function() { # doesn't fire after Ajax completes!
        console.log("loaded")
        $(".loader").hide(); # hides loading icon
        $("#recipe-index").animate({
            opacity: 1 # shows content
        }, 400);
    });
}

# one of the Ajax function that calls pinterest_it()
$(".togglebutton input").click(function () {
    console.log($(this).serialize());
    $.get(this.action, $('#recipes_search').serialize(), function() {
        pinterest_it();
    }, 'script')
});

我尝试过$(x).ready(...)ajaxComplete(),但都没有成功。也许有某种方法可以将$(x).load(...) 与特定元素而不是窗口一起使用来允许函数触发?我试过在 $("#recipe-index") 上调用它,但也没有用。

【问题讨论】:

    标签: javascript jquery ajax callback


    【解决方案1】:

    $(window).load 不会在 Ajax 请求成功/完成时触发。将该位移动到它自己的函数中:

      function handlePageRefresh () {
        console.log("loaded")
        $(".loader").hide(); # hides loading icon
        $("#recipe-index").animate({
            opacity: 1 # shows content
        }, 400);
     }
    

    然后在 $(window).load & Ajax 成功回调中调用它

    $(window).load(function() { # doesn't fire after Ajax completes!
        handlePageRefresh()
    });
    
    # one of the Ajax function that calls pinterest_it()
    $(".togglebutton input").click(function () {
        console.log($(this).serialize());
        $.get(this.action, $('#recipes_search').serialize(), function() {
          handlePageRefresh()
          pinterest_it();
        }, 'script')
    });
    

    【讨论】:

    • 这仍然不起作用,因为函数调用完成和窗口完全加载之间存在延迟。
    • 查看我的控制台,我可以看到有一个完成的 200 请求。完成后,我想调用我的函数(在你的情况下,handlePageRefresh())
    猜你喜欢
    • 2019-09-05
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2013-02-18
    相关资源
    最近更新 更多