Javascript 有没有办法等待 AJAX 响应并停止执行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12615169/
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
Is there any way to wait for AJAX response and halt execution?
提问by OneMore
Here is some code I'd like to execute. I'd like to wait for AJAX response so I can return something from the server. Any way to achieve this?
这是我想执行的一些代码。我想等待 AJAX 响应,以便我可以从服务器返回一些东西。有什么方法可以实现这一目标吗?
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
return data;
}
});
//Wait for AJAX (???)
}
var response = functABC();
采纳答案by Alexander Presber
New, using jquery's promise implementation:
新的,使用 jquery 的 promise 实现:
function functABC(){
// returns a promise that can be used later.
return $.ajax({
url: 'myPage.php',
data: {id: id}
});
}
functABC().then( response =>
console.log(response);
);
Nice read e.g. here.
不错的阅读,例如这里。
This is not "synchronous" really, but I think it achieves what the OP intends.
这实际上不是“同步”,但我认为它实现了 OP 的意图。
Old, (jquery's async
option has since been deprecated):
旧的,(jquery 的async
选项已被弃用):
All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify
所有 Ajax 调用都可以异步完成(使用回调函数,这将是在 'success' 键之后指定的函数)或同步完成 - 有效地阻塞并等待服务器应答。要获得同步执行,您必须指定
async: false
like described here
就像这里描述的那样
Note, however, that in most cases asynchronous execution (via callback on success) is just fine.
但是请注意,在大多数情况下异步执行(通过成功回调)就可以了。
回答by dome2k
When using promises they can be used in a promise chain. async=false will be deprecated so using promises is your best option.
使用承诺时,它们可以在承诺链中使用。async=false 将被弃用,因此使用 Promise 是您最好的选择。
function functABC() {
return new Promise(function(resolve, reject) {
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
resolve(data) // Resolve promise and go to then()
},
error: function(err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
functABC().then(function(data) {
// Run this when your request was successful
console.log(data)
}).catch(function(err) {
// Run this when promise was rejected via reject()
console.log(err)
})
回答by slebetman
The simple answer is to turn off async
. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.
简单的答案是关闭async
。但这是错误的做法。正确的答案是重新思考如何编写其余代码。
Instead of writing this:
而不是写这个:
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
return data;
}
});
}
function foo () {
var response = functABC();
some_result = bar(response);
// and other stuff and
return some_result;
}
You should write it like this:
你应该这样写:
function functABC(callback){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: callback
});
}
function foo (callback) {
functABC(function(data){
var response = data;
some_result = bar(response);
// and other stuff and
callback(some_result);
})
}
That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.
也就是说,不是返回结果,而是传入需要做的代码作为回调。正如我所展示的,回调可以嵌套到与函数调用一样多的级别。
A quick explanation of why I say it's wrong to turn off async:
快速解释为什么我说关闭异步是错误的:
Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.
关闭 async 会在等待 ajax 调用时冻结浏览器。用户无法点击任何东西,无法滚动,在最坏的情况下,如果用户内存不足,有时当用户将窗口拖离屏幕并再次拖入时,他会看到空白区域,因为浏览器被冻结并且无法重绘。对于像 IE7 这样的单线程浏览器,情况更糟:所有网站都冻结了!遇到这种情况的用户可能会认为您的网站有问题。如果您真的不想异步执行,则只需在后端进行处理并刷新整个页面即可。至少不会觉得有问题。
回答by johannes
There is no need to wait for an Ajax-response. You can load your data in the head-section of your application:
无需等待 Ajax 响应。您可以在应用程序的 head-section 中加载数据:
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
sessionStorage.setItem('mydata', data);
}
});
}
Then when the window.load event has fired, your data will be available:
然后当 window.load 事件触发时,您的数据将可用:
alert(sessionStorage.getItem('mydata'));
回答by Anil Kumar
use async:false
attribute along with url and data. this will help to execute ajax call immediately and u can fetch and use data from server.
使用async:false
属性以及 url 和数据。这将有助于立即执行 ajax 调用,您可以从服务器获取和使用数据。
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
async:false
success: function(data) {
return data;
}
});
}
回答by Snake Eyes
Method 1:
方法一:
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
return data;
},
complete: function(){
// do the job here
}
});
}
var response = functABC();
Method 2
方法二
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
async: false,
success: function(data) {
return data;
}
});
// do the job here
}