当另一个结束时执行一个功能

时间:2013-11-09 11:22:52

标签: jquery ajax

我正在将内容从JSON文件加载到HTML结构中,并希望等到在显示HTML之前加载JSON内容,有没有办法可以执行这行代码:{{1} } $('#wrapper').animate({opacity:1});何时完成?

loadContent();

4 个答案:

答案 0 :(得分:2)

将代码添加到success回调:

success: function(source){
    data = source;
    showStartpage(data);
    $('#wrapper').animate({opacity:1});
},

答案 1 :(得分:1)

$('#mch-overlay-content').load('layer_already.html', function() {
        loadContent(function() {
            $('#wrapper').animate({opacity:1});
        });
});

 function loadContent(callback){ 
        $.ajax({
            url: "json/" + language + "/content.json",
            data: "nocache=" + Math.random(),
            type: "GET",
            cache : false,
            contentType: "application/json",
            dataType: "json",
            success: function(source){
                data = source;
                showStartpage(data);
                callback();
            },
            error: function(data){
                alert("Failed to load content");
            }
        }); 



    }

    function showStartpage(){
            $("#game-logo a").addClass(language);
            $(".start .text3").html(data[language]['startpage']['text3']);
            $(".start .text4").html(data[language]['startpage']['text4']);
            $(".start .text5").html(data[language]['startpage']['text5']);
            $(".start .text6").html(data[language]['startpage']['text6']);
            $(".start .text7").html(data[language]['startpage']['text7']);
    }

答案 2 :(得分:0)

当然!将包装动画放在ajax success函数

的末尾
function loadContent()
{ 
    $.ajax(
    {
        url: "json/" + language + "/content.json",
        data: "nocache=" + Math.random(),
        type: "GET",
        cache : false,
        contentType: "application/json",
        dataType: "json",
        success: function(source)
        {
            data = source;
            showStartpage(data);
            $('#wrapper').animate({opacity:1}); // <- place it here
        },
        error: function(data){
            alert("Failed to load content");
        }
    }); 
}

答案 3 :(得分:0)

您可以使用延迟:

$('#mch-overlay-content').load('layer_already.html', function() {
    var dfd = loadContent();
    dfd.done(function(){
        $('#wrapper').animate({opacity:1});
    });
});

function loadContent(){ 
    return $.ajax({
        url: "json/" + language + "/content.json",
        data: "nocache=" + Math.random(),
        type: "GET",
        cache : false,
        contentType: "application/json",
        dataType: "json",
        success: function(source){
            data = source;
            showStartpage(data);
        },
        error: function(data){
            alert("Failed to load content");
        }
    }); 
}

当然,如果没有可能直接将动画放入成功回调