jQuery延迟对象与嵌套的ajax调用 [英] jQuery deferred object with nested ajax calls

查看:56
本文介绍了jQuery延迟对象与嵌套的ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是我的ajax调用必须按特定顺序执行。我在其他情况下使用过jQuery Deferred对象,但似乎无法找到使这种行为正常的方法。

I have a situation in which my ajax calls must perform in a particular order. I have used jQuery Deferred objects in other situations, but cannot seem to find a way to make this behave appropriately.

我有一个执行多个<$ c的函数$ c> ajax 请求在其生命周期内。一些请求将在成功回调其他请求期间执行。

I have a function which performs a number of ajax requests in it's lifetime. Some of the requests will be performed during the success callback of other requests.

我的问题:有没有办法将所有嵌套的延迟对象返回到原始 $。什么时候打电话?

My question: is there a way to return all nested deferred objects to the original $.when call?

一个简单的例子是:

function nestedAjax() {
    $.get("/", function(){
        console.log("First ajax done.");
        $.get("/", function(){
            console.log("Second ajax done.");
        });
    });
};

我正在尝试使用 nestedAjax 函数使用 $。when() $。done()如下:

I am trying to have the nestedAjax function to use $.when() and $.done() like so:

$.when(nestedAjax()).done(function(){
    console.log("Complete");
});​

控制台输出读数:

> First ajax done.
> Second ajax done.
> Complete.

我可以返回第一个获取来实现这个:

I can return the first get to achieve this:

> First ajax done.
> Complete.
> Second ajax done.

但显然这不是我要求的。任何帮助将不胜感激。

But obviously this is not what I require. Any help would be appreciated.

推荐答案

这实际上非常简单。虽然所有的AJAX调用都是Deferred对象,但我仍然使用一个方法本身。

It's actually quite simple. Though all the AJAX calls are Deferred objects, I still use one for the method itself.

function nestedAjax() {
    var dfd = $.Deferred();
    $.get("/echo/json/", function(){
        console.log("First ajax done.");
        $.get("/echo/json/", function(){
             console.log("Second ajax done.");
            dfd.resolve();
        });
    });

    return dfd.promise();
};

这篇关于jQuery延迟对象与嵌套的ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆