File request . txt via AJAX

Asked

Viewed 1,173 times

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:

inserir a descrição da imagem aqui

The error that appears on the console:

inserir a descrição da imagem aqui

Please... wait for us! Thank you!

2 answers

3

You need to use the webserver on both ends. The code is OK, but the screenshot shows that the ajax.html is being accessed in the browser with file:///. You need to access it with HTTP as well.

  • 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

  • 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).

2


Policy of the same origin

There is a security feature in the browsers called Same-origin policy (Policy of the same origin) which is responsible for restricting access to available resources on servers other than the server from which the current page came. This policy is important because it prevents a website from accessing your personal data from another site.

Because this policy is important?

Imagine that you access a page on a malicious website. This page, without your notice, could carry out an AJAX request to another site (a social network, internet banking). If you are logged in to this other site, the site will have full access to all information visible on it. This would be a giant security breach.

Therefore, browsers restrict, by default, access to any resource that does not come from the same origin as the page trying to access it.

Solutions

Your problem matches this constraint: your text file is available in the domain localhost, while the page trying to access it is being recovered via local file system (note the URL: file:///C:/Users/...). Soon the browser blocks access.

The best solution to your problem is to make your HTML page available on the same server as your text file (your Apache instance) and access the page there (something like http://localhost/ajax.html). This will make the browser identify that the resource is in the same domain as the page and allow access.

In other more complex cases, where it is really necessary that pages access resources in different domains one can configure the server to allow such access through HTTP headers CORS (cross-origin Resource sharing). On your server you can set arbitrary rules for which domains to allow or deny access to certain domains, including being able to do so dynamically.

  • Thank you so much for the full answer! E worked by putting it in the same origin! Although I’m not studying this yet, will I be able to request JSON file this way as well? Could you ask me this question? Thanks again!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.