jQuery docs强烈建议您在执行 $.ajax
请求时不要将 async
设置为 false
。
但是,我看到常见的 solutions要解决同步性问题,就需要这样做。然后我看到人们chastised违背文档的建议。
话虽如此,我尝试使用 promise避免使用 async:false
但运气不佳。
这是我正在使用的代码。我有一个调用 addToOrder
的 onclick 事件:
function saveTemplate() {
var formData = getFormData();
return $.ajax({
type: "POST",
url: "/p/session/save/" + sessionid + "/template/<?php echo $templateID ?>/",
data: formData,
async: true,
success: function(msg){
var rsp = $.parseJSON(msg);
if (rsp.response === 'Saved') {
sessionid = rsp.sessionid;
$("#save-preview-data-response").html(" " + rsp.response).fadeIn(100).delay(1000).fadeOut(1000);
} else {
$("#save-preview-data-response").css('color','#ff0000').html(" " + rsp.response).fadeIn(100).delay(1000).fadeOut(1000);
}
}
});
}
function addToOrder() {
var saved = saveTemplate();
var issaved;
saved.success(function(e) {
var rsp = $.parseJSON(e);
issaved = (rsp.response == 'Saved') ? true : false;
});
if(issaved) {
$.ajax({
type: "POST",
url: "<?php echo $baseURL; ?>addToOrder/respond/json",
data: "sid=" + sessionid,
async: true,
success: function(msg){
var rsp = $.parseJSON(msg);
if (rsp.response === 'Saved') {
alert(msg);
}
}
});
}
}
issaved
将始终评估为 false,因为它是在 saveTemplate
有时间运行之前评估的。我找到的唯一解决方案是设置 async:false
但我正在认真对待我所看到的警告,并且不愿意这样做。还有哪些其他解决方案?
最佳答案
Tactics to avoid using async:false with jQuery?
学会喜欢回调。 :-) 当人们这样做时:
// The synchronous way
function doSomething() {
var foo;
$.ajax({
url: "/the/url",
async: false,
success: function(response) {
foo = response.foo;
}
});
return foo;
}
// ...somewhere else, we use it
function flurgle() {
var bar = /* go get `bar` from somewhere */;
var x = 52;
if (doSomething() === bar) {
x -= 10;
}
niftyFunctionUsing(x);
}
...事件驱动的异步方式实际上并没有太大不同:
// The asynchronous way
function doSomething(callback) {
$.ajax({
url: "/the/url",
success: function(response) {
callback(response.foo);
}
});
}
// ...somewhere else, we use it
function flurgle() {
var bar = /* go get `bar` from somewhere */;
var x = 52;
doSomething(function(foo) {
if (foo === bar) {
x -= 10;
}
niftyFunctionUsing(x);
});
}
由于回调经常涉及闭包(上面的回调涉及闭包,这就是我们访问 x
和 bar
的方式),我博客中的这篇文章可能会有所帮助:Closures are not complicated
关于jquery - 避免使用异步的策略 :false with jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6902174/