我想向服务器发送XMLRequest,然后将用户重定向到首页 我有:
var posts = new XMLHttpRequest();
var api="XXXXXXXXXX";
posts.open("GET", api+user+"/"+password+"/"+id+"/"+latitude, true);
posts.send();
window.location = "index.html"
如果我只运行没有重定向的代码,那么它的效果很好,但如果我有重定向,则API GET请求失败。有人可以向我解释我错过了什么吗?
答案 0 :(得分:2)
请求是异步,这意味着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();