Aymen Kareem Aymen Kareem - 18 days ago 9
Javascript Question

Why XMLHttpResponse doesn't work

I have the following code which I can't figure out why it didn't work:

<script>
var request = new XMLHttpRequest();
request.open("GET", "textfile.txt", true);
request.onreadystatechange = function() {
if(request.readyState===4) {
alert(request.responseText);
}
};
request.send(null);

</script>

<html>
<head>
</head>
<body>
</body>
</html>


I'm sure that I have the file name "textfile.txt" in the same directory as the html file. What I get is only an empty javascript alert but I can't display the text file text.

EDIT:
I noticed that I get the following error when I viewed the developer tools this error at the request.send(null) line:

XMLHttpRequest cannot load file:///D:/textfile.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Answer

You need a web server, such as Nginx, Apache and IIS and then put your HTML file and textfile.txt in the same domain.