[英]XMLHttpRequest status 0 but responseText correct
I have the following HTML file, test.html : 我有以下HTML文件test.html :
<html>
<head>
<title>Test</title>
</head>
<body>
<p>This is a test</p>
</body>
</html>
From the console, on a separate file in the same directory, I enter 从控制台,在同一目录中的单独文件中,输入
var request = new XMLHttpRequest();
request.open("GET", "test.html", true);
request.send(null);
Now, request.responseText
contains the contents of the HTML file, but request.status
and request.statusText
are 0 and "" respectively. 现在,
request.responseText
包含HTML文件的内容,但是request.status
和request.statusText
分别为0和“”。 I've seen a hundred questions with the responseText
being empty and the status 0, but I can't find anything with the responseText
acting correctly and the statusText
not. 我已经看到了一百个问题,其中
responseText
为空且状态为0,但是我找不到任何内容,而responseText
行为正确,而statusText
不是。 Why might this be happening? 为什么会这样呢? Any ideas?
有任何想法吗?
Before you START programming for Web you should understand what is HTTP , WebServer , Client , Protocol , Request , Response and Status Code . 在开始为Web编程之前,您应该了解什么是HTTP , WebServer , 客户端 , 协议 , 请求 , 响应和状态代码 。
Protocol file://
don't work with XMLHttpRequest
by browser security, prefer http://
. 由于浏览器的安全性,协议
file://
不能与XMLHttpRequest
,而是使用http://
。 For use http://
in your PC/Machine install Apache or Nginx 要在PC /机器中使用
http://
,请安装Apache或Nginx
To start working with "WEB" is advisable to know a programming language and perhaps a framework: 建议您开始使用“ WEB”,以了解一种编程语言,甚至是一个框架:
Ajax in Async-mode requires onreadystatechange
异步模式下的Ajax需要
onreadystatechange
Ajax ( "A"synchronous Javascript and XML ): Ajax( “ A”同步Javascript和XML ):
var request = new XMLHttpRequest();
request.open("GET", "test.html", true);//true is "async"
request.onreadystatechange = function (event) {
if (request.readyState==4) {
console.log("status: "+request.status);
console.log("response: "+request.responseText);
}
};
request.send(null);
"SJAX" ("S"ynchronous Javascript and XML): “ SJAX”(“ S”同步Java语言和XML):
var request = new XMLHttpRequest();
request.open("GET", "test.html", false);//false is "sync"
request.send(null);
if (request.readyState==4) {
console.log("status: "+request.status);
console.log("response: "+request.responseText);
}
Prefer asynchronous mode, so that you can work multiple events without a need to wait for the other and also avoid freezing the "javascript". 首选异步模式,这样您就可以处理多个事件,而无需等待其他事件,并且还避免冻结“ javascript”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.