ajax synchronous call with timeout

后端 未结 2 1519
北恋
北恋 2020-12-18 06:00

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.ajaxtoolbo

相关标签:
2条回答
  • 2020-12-18 06:15

    I don't believe it's possible to set a timeout on a synchronous call. When you set "async:false", I believe the browser actually locks up while waiting for the response. You should only use a synchronous request if you absolutely need to (because of the browser locking up).

    0 讨论(0)
  • 2020-12-18 06:38

    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");
        }
    });
    
    0 讨论(0)
提交回复
热议问题