javascript 如何阻止 ajax 调用(我希望它阻止)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12213889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:36:40  来源:igfitidea点击:

how to block on ajax call (I want it to block)

javascriptajax

提问by Poni

Ajax uses callbacks, as it's Asynchronous.

Ajax 使用回调,因为它是A同步的。

I want my call to the remote URL block until there's some answer, exactly as in Ajax, but without the asynchronous part, or shall I say I want to make a JAX call.

我希望我调用远程 URL 块,直到有一些答案,就像在 Ajax 中一样,但没有异步部分,或者我应该说我想进行 JAX 调用。

Is there any technique to make the following happen (uses JQuery) (... solution with JQuery or anything else):

是否有任何技术可以使以下情况发生(使用 JQuery)(...使用 JQuery 或其他任何解决方案):

function get_data() {
    $.ajax({
        type : "POST",
        url : "/foo"
    }).done(function(data, textStatus, jqXHR) {
        return data;
    }).fail(function(jqXHR, textStatus) {
        return null;
    });
}

var data = get_data();
// process `data`

I'm just wondering - want to learn.

我只是想知道 - 想学习。

Actually there are times where blocking until a reply would fit fine. I'm not saying I want the browser to block, just the script runtime.

实际上,有时阻塞直到回复才合适。我不是说我要阻止浏览器,只是阻止脚本运行时。

回答by MarcoK

You can simply set the async : falseboolean when using jQuery (check the docs). Take note: As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the complete/success/error callbacks.

您可以async : false在使用 jQuery 时简单地设置布尔值(检查文档)。注意:从 jQuery 1.8 开始,不推荐使用带有 jqXHR ($.Deferred) 的 async: false ;您必须使用完整/成功/错误回调。

If you don't want to use jQuery or want to know what's going on under the hood, read this.

如果您不想使用 jQuery 或想知道幕后发生的事情,请阅读此

xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Do wonder why you don't want it to be async though...

不知道为什么你不希望它是异步的......