Ajax navigation error ("Xmlhttprequest cannot load...")

Asked

Viewed 3,362 times

4

I’m trying to use a browsing without refresh on the page, but when I click on the link, give this error:

XMLHttpRequest cannot load file:///Caminho.../paginas/login.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I used this login.html only as a test.

filing cabinet navegacao.js, what makes the magic happen:

$(document).ready(function(){
        var content = $('#conteudo');

        //pre carregando o gif
        loading = new Image(); loading.src = 'imgs/loading.gif';
        $("#c_i_up a").click(function(e) {
            e.preventDefault();
            content.html( '<img src="imgs/loading.gif" />' );

            var href = $( this ).attr('href');
            $.ajax({
                url: href,
                success: function( response ){
                    var data = $('#conteudo').html(response);

                    //apenas atrasando a troca, para testar o loading
                    window.setTimeout( function(){
                        content.fadeOut('slow', function(){
                            content.html( data ).fadeIn();
                        });
                    }, 100 );
                }
            });

        });
    });

filing cabinet index.html abridged:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="js/navegacao.js"></script>
</head>
<body>
    <div id="conteudo">
        <div id="c_i_up">
            <a href="paginas/login.html">Teste</a>
        </div><!--c_i_up-->                 

    </div><!--conteudo-->
</body>
</html>

Note: I used Chrome and Firefox browser to test.

1 answer

8


The error is happening because you are accessing the URL as a simple path on your computer. If you put these scripts inside a webserver (Apache, IIS) this error will not occur.

Browsers have something called "same domain policy", which, briefly, means that the browser will only upload files via Xmlhttprequest if the destination is in exactly the same origin domain (which is in the browser’s address bar).

When you open files in your browser, the address bar starts something like:

file:///arquivos/pagina.html 

it has a null origin. It would be necessary to access through a webserver, where the address would look something like:

http://localhost/pagina.html
  • I had forgotten this rs, is what I was doing just to test it. Obg!

Browser other questions tagged

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