0
I’m starting in my studies with Javascript with server interactions, and right away I can’t recover a text file to be shown via a Javascript Alert. From what I’ve studied, the file needs to be on a server. In other words, to make a request you need to do it through an "http://". At first, I’m doing it locally with Apache. And yet, it’s not working.
Follows the code:
window.onload = function(){
document.getElementById("button").onclick = function(){
//alert("Ok");
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if( ajax.readyState == 4) {
alert(ajax.responseText);
}
}
ajax.open("POST", "http://localhost/ajax/texto.txt");
ajax.send(null); //Inicia a requisição para o servidor.
return false;
}
}
<h1 id="button">Teste</h1>
The result that appears to me:
The error that appears on the console:
Please... wait for us! Thank you!
Adding Information to the Answer: This type of request cannot be made using
file:///
because navigators impose a kind of "barrier" for security purposes. Look at that answer, that’s exactly what I want to explain: http://answall.com/a/56217/23262– Rafael Almeida
Does it need CORS?! All you need to do is change the URL you are using in the browser. The reason is the barrier you mentioned yourself (policy between domains / cross-Domain policy).
– bfavaretto