Reputation: 3
I have the following HTML file, 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. 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. Why might this be happening? Any ideas?
Upvotes: 0
Views: 712
Reputation: 9754
Before you START programming for Web you should understand what is HTTP, WebServer, Client, Protocol, Request, Response and Status Code.
Protocol file://
don't work with XMLHttpRequest
by browser security, prefer http://
.
For use http://
in your PC/Machine install Apache or Nginx
To start working with "WEB" is advisable to know a programming language and perhaps a framework:
Ajax in Async-mode requires onreadystatechange
Ajax ("A"synchronous Javascript and 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):
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".
Upvotes: 1