JavaScript XMLHttpRequest()和重定向

Joh*_*own 3 html javascript redirect

我想将XMLRequest发送到服务器,然后将用户重定向到首页,到目前为止,我拥有:

var posts = new XMLHttpRequest();
var api="XXXXXXXXXX";
posts.open("GET", api+user+"/"+password+"/"+id+"/"+latitude, true);
posts.send();

window.location = "index.html"
Run Code Online (Sandbox Code Playgroud)

如果我只运行没有重定向的代码,那么效果很好,但如果有重定向,则API GET请求失败。有人可以向我解释我所缺少的吗?

tos*_*skv 7

这些请求是异步的,这意味着window.location在执行之前不会等待请求完成。这导致导航离开当前页面,浏览器取消请求。

要解决此问题,您必须等待请求完成才能导航。您可以通过侦听请求的状态更改来执行此操作。

var posts = new XMLHttpRequest();
posts.onreadystatechange = function() { // listen for state changes
  if (posts.readyState == 4 && posts.status == 200) { // when completed we can move away
    window.location = "index.html";
  }
}
posts.open("GET", api+user+"/"+password+"/"+id+"/"+latitude, true);
posts.send();
Run Code Online (Sandbox Code Playgroud)