ajax synchronous call with timeout

拥有回忆 提交于 2019-12-18 05:04:10

问题


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


回答1:


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");
    }
});



回答2:


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



来源:https://stackoverflow.com/questions/2195259/ajax-synchronous-call-with-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!