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
1.1k views
in Technique[技术] by (71.8m points)

asynchronous - ajax synchronous call with timeout

New to ajax, so asking a very basic question.

-- Is there no way to make a Synchronous ajax call (async:false) with timeout set on it.?

http://www.ajaxtoolbox.com/request/

Timeout works perfect with Asynchronous call though in my application, but for one particular scenario, I need a Synchronous call (the javascript should actually wait untill it hears back from the server), and this also works fine. But I need to handle a scenario where the sever could take long and a ajax timeout may be called.

Is there any other piece of standard documentation for ajax I could refer to?

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Basically, during a synchronous ajax request, the browser is blocked and no javascript can be executed while the browser is blocked. Because of this, jQuery can't abort the ajax request after a set timeout because jQuery is javascript and javascript can't be executed while the browser is blocked. This is the primary flaw in synchronous ajax.

Anytime you might want a synchronous request, you should instead use an asynchronous one with what should happen afterwards in the callback, as shown below;

$.ajax({
    url : 'webservices.php',
    timeout: 200,
    dataType : 'json',
    data : {
        'cmd' : 'ping',
    },
    success : function(data, textStatus) {
        $.ajax({
            url : 'webservices.php',
            async: false,
            dataType : 'json',
            data : {
                'cmd' : 'feedback',
                'data' : data,
                'userinfo' : window.dsuser
            },
            success : function(data, textStatus) {
                // success!
                Status("Thanks for the feedback, "
                    + window.dsuser.user + "!");
            }
        });
    },
    error : function(jqhdr, textStatus,
                     errorThrown) {
        Status("There was trouble sending your feedback. Please try again later");
    }
});

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

1.4m articles

1.4m replys

5 comments

57.0k users

...