XMLHttpRequest 的空响应

Empty response of XMLHttpRequest

在我的 Java Web 应用程序中,我正在调用 ajax 请求,如下所示。

<script type="text/javascript">
function selectTableHandler() {
    console.log("indise selectTableHandler");
    var xhttp = new XMLHttpRequest();

    var selectedTable = document.getElementById('selectTable').value;
    alert(selectedTable);
    xhttp.open("GET", "populateTableColumList.action?tablename="
            + selectedTable, true);
    xhttp.send();
    console.log(xhttp.responseText);
}
</script>

操作正在调用,returns 状态代码 200,如下所示。

Remote Address:[::1]:8080
Request        URL:http://localhost:8080/ReportBuilder/populateTableColumList.action?tablename=films
Request Method:GET
Status Code:200 OK

但是,它给出了 XMLHttpRequest 的空响应。 console.log(xhttp.responseText); 行什么都不打印。此外,控制台日志中没有错误。

如有任何建议,我们将不胜感激。

谢谢

您的 ajax 请求是异步的。这意味着它 returns 一段时间后的结果。您需要为 onloadonreadystatechange 安装事件处理程序才能获得结果。

有很多 Ajax 教程介绍如何执行此操作。这里有一些有用的参考资料:

https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

如果你想使用 vanilla js,你必须附加事件处理程序 onreadystatechange 来处理响应,但我的建议是不要使用 vanilla js,使用像 jQuery 这样的库来启动 ajax 请求。它会更容易,并且 运行 在所有类型的浏览器上都不会出现问题。参见 here。如果你想要香草 js,这里有一个示例片段:

xhttp.onreadystatechange = function() {
        if (xhttp.readyState == XMLHttpRequest.DONE ) {
           if(xhttp.status == 200){
              console.log(xhttp.responseText);
           }

        }
    }

您需要添加一个回调函数来获取ajax请求的结果。

xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    console.log(xhttp.responseText);
  }
}