Javascript 在所有 ajax 调用完成后如何重新加载页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4020123/
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
How do I reload the page after all ajax calls complete?
提问by Legend
The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
用户第一次访问我的网站时,我会使用几个 ajax 调用从各种来源获取大量信息。ajax调用完成后如何重新加载页面?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData
function) and uses them to get more information from a thirdparty service (getInformation
function). This getInformation
function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
所以代码的作用是,它获取新用户(populateData
函数)的预定义标识符列表,并使用它们从第三方服务(getInformation
函数)获取更多信息。此getInformation
函数查询第三方服务器,一旦服务器返回一些数据,它就会通过另一个 ajax 调用将该数据发送到我的服务器。现在我需要的是一种确定所有 ajax 调用何时完成的方法,以便我可以重新加载页面。有什么建议?
回答by Nick Craver
In your getInformation()
call you can call location.reload()
in your success
callback, like this:
在您的getInformation()
通话中,您可以调用location.reload()
您的success
回调,如下所示:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any furtherajax calls complete, you can use the ajaxStop
event, like this:
要等到任何进一步的ajax 调用完成,您可以使用ajaxStop
event,如下所示:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
回答by Blahhh
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
您可以重定向到 server.php 文件中使用 header('Location: html-page'); 定义函数的同一页面。
回答by Akki
//document.location.reload(true);
window.location = window.location;