javascript - 即使发送了响应,XMLHttpRequest 也只能达到 readystate 1
问题描述
我正在尝试向我在 app.js 中设置的节点服务器发送一个 httprequest。在 app.js 中定义了一个名为 allSnippets 的特定端点,当我运行http://localhost:3000/allSnippets时,它按预期工作,但是当我在 html 文件中创建一个应该向 app.js/allSnippets 发送 XMLHttpRequest 的按钮时,就绪状态永远不会超过 1。总的来说,我想达到就绪状态 4 并处理响应,但我选择更改“嗨”的颜色来测试我达到的就绪状态,因为我从未收到任何响应。此 html 文件位于名为“public”的目录中。包含“public”的目录也包含 app.js。
<p id = "text">Hi</p>
<button type = "button" onclick = "displaySnips()">View snippets</button>
<script>
function displaySnips() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 2){
document.getElementById("text").style.color = 'red';
}
else if (this.readyState == 1){
document.getElementById("text").style.color = 'blue';
}
else if (this.readyState == 3){
document.getElementById("text").style.color = 'green';
}
else if (this.readyState == 4 && this.status == 200) {
document.getElementById("text").style.color = 'white';
}
}
xhttp.open("GET", "../app.js/allSnippets", true);
xhttp.send();
}
</script>
关于为什么我没有达到就绪状态 4 的任何想法?
解决方案
推荐阅读
- python - 查找两个不同列表的元素之间的距离
- nginx - 使用 Flask 重定向在浏览器中保留 URL
- javascript - 在 JQuery 中使用切换但在单击外部 div 时需要关闭
- nginx - 要默认 ngix 配置,请添加子目录
- python-3.x - Python中的数字游戏
- go - 无法通过 Go 中的 slack 发送通知
- python - 使用字典从字符串中检索字典列表
- java - 如果我们尝试将 toString 应用于 String Literal 会发生什么?
- ruby-on-rails - 实例变量在黄瓜步骤中不可用
- angular - 在 Angular 的 HTML 中动态包含数组对象变量