javascript 只有在ajax请求完全完成后才执行js函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8271618/
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
Execute a js function only after the ajax request fully compleated
提问by Shibin V.M
I want to execute a js function only after the jquery ajax call fully completed.(After Success and Error Events completed). ie after ajax call puts incoming data to an element.
我只想在 jquery ajax 调用完全完成后执行一个 js 函数。(成功和错误事件完成后)。即在ajax调用将传入数据放入元素之后。
How to achive this.
如何实现这一目标。
回答by Nicola Peluchetti
You should use $.ajaxComplete();
你应该使用$.ajaxComplete();
$(document).ajaxComplete(function() {
alert("compete");
});
this would be triggered after every Ajax call you make on the page
这将在您在页面上进行的每次 Ajax 调用后触发
otherwise you use ajax()and set the complete property
否则你使用ajax()并设置完整的属性
$.ajax({
url: "myurl",
complete: function(){
alert("complete");
}
//set all the other options as usual
回答by tvanfosson
You can use the callback to any of the jQuery AJAX methods to delay execution of another function until after the request is complete.
您可以使用任何 jQuery AJAX 方法的回调来延迟另一个函数的执行,直到请求完成。
Example:
例子:
$.post('/some/url', somedata, function() {
// put the code you want to execute on completion here
});
For more complicated scenarios, use the actual ajaxmethod which gives you hooks for success, completion, error and other events. Typically, you'd only need success and error.
对于更复杂的场景,请使用实际的ajax方法,它为您提供成功、完成、错误和其他事件的挂钩。通常,您只需要成功和错误。
$.ajax( '/some/url', {
data: somedata,
type: 'post',
success: function(result) {
// success code execution here
},
error: function(xhr,status,error) {
// error code here
},
complete: function(xhr,status) {
// completion code here
}
});
回答by Adam Rackis
If you want to do this for a particular call, then the complete
function is likely what you need. If you want this to be global, for all ajax calls, then Nicola's answer should be what you need.
如果您想为特定调用执行此操作,那么该complete
函数可能就是您所需要的。如果您希望这是全球性的,对于所有 ajax 调用,那么 Nicola 的回答应该是您所需要的。
Here's the jQuery documentationfor Ajax calls.
这是Ajax 调用的 jQuery文档。