如何嵌入jQuery。当使用回调调用时?

时间:2012-10-18 22:05:02

标签: javascript ajax jquery asynchronous

我有一个加载部分的函数。

function loadSection(sectionId, onLoaded) {
    $.when(
        loadTemplate(sectionId),
        // etc
    )
    .then(function () {
        // removed for brevity
    }
}

loadTemplate功能中,我淡出当前模板,在淡出后我加载新模板。

function loadTemplate(sectionId) {
    // Fade out current template.
    return $content.fadeOut(function () {
        // After fade out, load new template via ajax.
        $.ajax({
            url: settings.apiUrl + 'GetSectionTemplate',
            data: { sectionId: sectionId },
            type: 'post',
            success: function (template) {
                // Add new content and fade in new template.
                $content
                    .html(template)
                    .fadeIn();
            }
        });
    });
}

问题是$.when仅在继续前等待fadeOut功能完成。我需要它等待fadeOut和ajax调用完成,但我需要ajax调用才能在fadeOut完成后执行。

3 个答案:

答案 0 :(得分:2)

创建一个延迟对象,返回它,然后在ajax完成时解析它:

function loadTemplate(sectionId) {
    var deferred = $.Deferred();
    $content.fadeOut(function () {
        $.ajax({
            url: settings.apiUrl + 'GetSectionTemplate',
            data: { sectionId: sectionId },
            type: 'post',
            success: function (template) {
                $content.html(template).fadeIn();
                deferred.resolve();
            }
        });
    });
    return deferred;
}

答案 1 :(得分:1)

只需使用Array Promise对象推送到并返回即可。像

function loadTemplate(sectionId) {
    var promises = [ ];

    // Fade out current template.
    promises.push($content.fadeOut());
    promises.push($.ajax({
        url: settings.apiUrl + 'GetSectionTemplate',
        data: { sectionId: sectionId },
        type: 'post',
        success: function (template) {
            // Add new content and fade in new template.
            $content
                .html(template)
                .fadeIn();
        }
    }));

    return promises;
}

然后将其称为

$.when.apply( null,
    loadTemplate(sectionId)
).then(function() {
});

如果你需要更多地控制promise-objects解决顺序,或者你想拦截/过滤结果,你也可以使用.pipe()来某种 concat 这些承诺。

答案 2 :(得分:-1)

尝试将ajax调用同步:

 $.ajax({
    async: false,
    url: settings.apiUrl + 'GetSectionTemplate',
    ...
    ...
相关问题