Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

关于jQuery deferred 多个AJAX执行问题

我写了两个函数,分别是使用AJAX请求数据,为了能控制他们的执行顺序,也不想改变AJAX的异步开关,发现使用deferred写法后,fail和done方法都执行了

代码:

    function func1(dfd) {
         
            $.ajax({
                type: "POST",
                timeout: 10 * 1000,
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                data: { },
                url: ""
            }).done(function (msg) {
                dfd.resolve();
            }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                dfd.reject();
            });
        }

        return dfd;
    }
    
            function func2() {
        $.ajax({
            type: "POST",
            timeout: 5 * 1000,                
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: {  },
            url: ""
        }).done(function (msg) {
            }
        }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.status + "|" + XMLHttpRequest.statusText);
        });
    }
    
    $(document).ready(function () {            
        var defer = new $.Deferred();
        $.when(fucn1(defer)).done(func2()).fail(function () { alert("fail") });
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
你写的代码有问题,我帮你改了下:

function func1(dfd) {
     
        $.ajax({
            type: "POST",
            timeout: 10 * 1000,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: { },
            url: ""
        }).done(function (msg) {
            dfd.resolve();
        }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
            dfd.reject();
        });
        return dfd;
    }
    // return dfd;



        function func2() {
    $.ajax({
        type: "POST",
        timeout: 5 * 1000,                
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        data: {  },
        url: ""
    }).done(function (msg) {
        }
    }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest.status + "|" + XMLHttpRequest.statusText);
    });
}

$(document).ready(function () {            
    var defer = new $.Deferred();
    // func1
    $.when(func1(defer)).done(func2()).fail(function () { alert("fail") });
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...