0

According to Same Origin Policy, SOP shouldn't apply to file:// protocol, but why my code does not work? I am running this testing page from my local system and I have abc.txt in the same directory as the html page. If I change URL to http://www.google.com/, it does not work too. I don't understand why, could anyone explain?

<!doctype html>
<html lang="us">
<head>
    <meta charset="utf-8">
    <title>jQuery UI Example Page</title>
    <link href="css/sunny/jquery-ui-1.10.2.custom.css" rel="stylesheet">
    <script src="js/jquery-1.9.1.js"></script>
    <script src="js/jquery-ui-1.10.2.custom.js"></script>
    <script>
    $.support.cors = true;
    $(function(){
        $(".btn1").button().click(function(){
            $.ajax({

              url: "abc.txt"

            }).done(function(result) {
              alert("done");
              $(".content").html(result);
            }).fail(function() { 
                alert("error"); 
            });
        });

    });

    </script>
</head>
<body>

<button class="btn1">Click me!</button>

<div class="content"></div>

</body>
</html>

Edited: The console printed as below:

XMLHttpRequest cannot load file:///C:/Users/yc/Desktop/jquery%20ajax%20testing/jquery-ui-1.10.2.custom/jquery-ui-1.10.2.custom/abc.txt. Origin null is not allowed by Access-Control-Allow-Origin.

*It does not work for Firefox, IE too.

Sam YC
  • 10,725
  • 19
  • 102
  • 158

2 Answers2

3

This is not a bug, it's a security feature which you can't/won't get around on a client's computer.

In chrome you can disable it by adding the following flag on the command line

--disable-web-security

Firefox might have something similar but I don't know it. This is only useful for development purposes and you can't rely on this behaviour in your application.

You should really just use a server ...

Ilia Choly
  • 18,070
  • 14
  • 92
  • 160
  • The second option is no longer a valid circumvention - removed via edit. – smaudet Sep 29 '13 at 21:54
  • @smaudet Edit request denied. Leaving a comment about it is enough and then it will be up to the author of the answer for now to determine if the secondary option should be removed from the answer or not. – Simon Forsberg Sep 29 '13 at 22:28
0

A slightly safer command line flag than ''--disable-web-security'' is

--allow-file-access-from-files

This does not completely turn off all security features. Still also this flag should not be used in productive environments...

jdehaan
  • 19,700
  • 6
  • 57
  • 97