ajax到location.replace(ajax. responsetext)永远重新加载

ajax to location.replace(ajax.responseText) reloads forever

本文关键字:ajax 新加载 加载 responsetext location replace 永远      更新时间:2023-09-26

我不知道为什么会发生这种情况,而且没有相关文档:

<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>HideSite</h1>
<script>
var ajax;
if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
} else {
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
    location.replace(ajax.responseText);
}
if (navigator.userAgent == 'code') {
    ajax.open("POST", "location.txt", true);
    ajax.send();
}
</script>
</body>
</html>

location.txt包含文件的位置。

<标题>更新:

代替replace(),我插入这个:alert(ajax.responseText)。它这样做了三次,只有在第三次时窗口才真正包含任何东西。

if (ajax.responseText != undefined && ajax.responseText != "") {
        alert(ajax.responseText);
}

当我添加这个时,它只做了两次,两次都包含正确的字符串

在AJAX调用的生命周期中,onreadystatechange事件被击中多次;这些点击中的大多数实际上不会传递任何响应文本。就绪状态如下:

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

正如您所说的"在每次状态更改时"而不是"当响应准备好时",您的AJAX调用通常还没有收到响应。我建议修改您的事件以包含if语句,如下所示:

ajax.onreadystatechange = function() {
   if (ajax.readyState == 4) {   //WHEN RESPONSE IS READY
      location.replace(ajax.responseText);
   }
}