具体来说,它与默认值(async: true)有什么不同?
在什么情况下,我想显式设置async为false,它是否与防止页面上的其他事件发射有关?
具体来说,它与默认值(async: true)有什么不同?
在什么情况下,我想显式设置async为false,它是否与防止页面上的其他事件发射有关?
这有什么关系吗 阻止页面上的其他事件 从发射?
Yes.
将async设置为false意味着在调用函数中的下一个语句之前必须完成所调用的语句。如果你设置async: true,那么该语句将开始执行,无论async语句是否已经完成,下一个语句将被调用。
欲了解更多信息,请参阅: jQuery ajax成功匿名函数作用域
一个用例是在用户关闭窗口或离开页面之前进行ajax调用。这就像在用户可以导航到另一个站点或关闭浏览器之前删除数据库中的一些临时记录。
$(window).unload(
function(){
$.ajax({
url: 'your url',
global: false,
type: 'POST',
data: {},
async: false, //blocks window close
success: function() {}
});
});
From
https://xhr.spec.whatwg.org/#synchronous-flag
Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs. The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.
将async设置为false意味着ajax请求之后的指令必须等待请求完成。下面是必须将async设置为false的一种情况,以便代码正常工作。
var phpData = (function get_php_data() {
var php_data;
$.ajax({
url: "http://somesite/v1/api/get_php_data",
async: false,
//very important: else php_data will be returned even before we get Json from the url
dataType: 'json',
success: function (json) {
php_data = json;
}
});
return php_data;
})();
上面的例子清楚地解释了async:false的用法
通过将其设置为false,我们确保一旦从url中检索到数据,只有在此之后才返回php_data;被称为