javascript 加载ajax响应时jquery执行函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12125510/
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
jquery execute function while ajax response is loading
提问by eatonphil
How can I execute a function that will run while the client is waiting for the server response? Here is my code. I looked up and found a .load() function, but how does that fit into this? Any help would be great! Thanks
如何执行在客户端等待服务器响应时运行的函数?这是我的代码。我查了一下,发现了一个 .load() 函数,但它如何适应这个?任何帮助都会很棒!谢谢
$.ajax({
type: "POST",
url: "mail.php",
data: {name: name.val(), email: email.val(), phone: phone.val(), subject: subject.val(), message: message.val()}
}).done(function(){
alert("Your message was sent. We will be in contact with you shortly.");
window.location="index.html";
});
回答by Macdiesel
The very next line of code you write after You call $.ajax() will run while the browser is waiting for a response.
您在调用 $.ajax() 之后编写的下一行代码将在浏览器等待响应时运行。
So:
所以:
$.ajax();
yourAwesomeFN();
XhttpRequests are asynchronous. No extra work required.
XhttpRequests 是异步的。不需要额外的工作。
回答by Amin Eshaq
Have you looked in the "beforeSend" param.
您是否查看过“beforeSend”参数。
$.ajax({
type: "POST",
url: "mail.php",
data: {name: name.val(), email: email.val(), phone: phone.val(), subject: subject.val(), message: message.val()},
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
回答by moonwave99
You can't execute a function whileanother is being executed in JS, being it mono-threaded: you can do stuff beforeand afterthough - are you looking for a way to setup a message / spinner to be shown while waiting? Check beforeSendoption in $.ajax()
call:
你不能在 JS 中执行另一个函数时执行一个函数,因为它是单线程的:你可以在之前和之后做一些事情- 你是否正在寻找一种方法来设置在等待时显示的消息/微调器?在通话中检查beforeSend选项$.ajax()
:
$.ajax({
type: "POST",
url: "mail.php",
data: {name: name.val(), email: email.val(), phone: phone.val(), subject: subject.val(), message: message.val()}
beforeSend : function(){
// do your stuff here
}
}).done(function(){
alert("Your message was sent. We will be in contact with you shortly.");
window.location="index.html";
});