Error with Ajax navigation ("XMLHttpRequest can not load ...")

4

I'm trying to use a navigation without refresh on the page, but when I click the link, it gives 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.

file navegacao.js , which 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 );
                }
            });

        });
    });

file index.html summarized:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script><scripttype="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 the Chrome and Firefox browser to test.

    
asked by anonymous 07.02.2014 / 14:55

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 in short means that the browser will only load files via XMLHttpRequest if the destination is in exactly the same source domain (which appears in the browser's address bar) .

When you open files in your browser, where the address bar starts with 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
    
07.02.2014 / 15:08