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

Categories

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

async:false option not working in $.ajax() , is it depreciated in jQuery 1.8+ for all use cases?

I'm confused about using the async: false option with $.ajax(). According to the $.ajax() documentation:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

I don't know what jqXHR ($.Deferred) means. Is using async:false for any reason depreciated, or is jqXHR ($.Deferred) some sort of special use case?

I ask as I'm having trouble getting an $.ajax() call to happen asynchronously.This is with jQuery 1.8.2:

var ret = {};

$.ajax({
   async:           false,
    method:         'GET',
    contentType:    'application/json',
    dataType:       'jsonp',
    url:            '/couchDBserver',
    error:          myerr,
    success:        function(data) {

        var rows = data.rows;

        //something that takes a long time
        for(var row in rows) {
             ret[rows[row].key] = rows[row].value;
        }

        console.log('tick');
    }
});
console.log('tock');
console.log(JSON.stringify(ret))

My console output is:

tock
{}
tick

Am I doing something wrong, or am I doing something wrong?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

what it is saying is, if your request is async: false then you should not use ajax.done(), ajax.fail() etc methods to register the callback methods, instead you need to pass the callback methods using success/error/complete options to the ajax call

correct

$.ajax({
    async: false,
    success: function(){
    },
    error: function(){
    },
    complete: function(){
    }
})

wrong

$.ajax({
    async: false
}).done(function(){
}).fail(function(){
}).always(function(){
})

if async: true //not specified

correct

$.ajax({
}).done(function(){
}).fail(function(){
}).always(function(){
})

or

$.ajax({
    async: false,
    success: function(){
    },
    error: function(){
    },
    complete: function(){
    }
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...