10

I created simple html file with simple ajax.

index.html:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; Charset=UTF-8">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
    <div id="content"></div>

    <script>
        function show()
        {
                $.ajax({
                url: "2.html",
                cache: false,
                success: function(html){
                    $("#content").html(html);
                }
            });
        }

        $(document).ready(function(){
            show();
            setInterval('show()',1000);
        });
    </script>

</body>
</html>

File 2.html located in the same directory as the file index.html. And contains for example:

 <p>ssss hkl jh lkh <b>d1111</b></p>

When I run the index.html on the webserver, everything works. But if you run file index.html on the computer as a local file ajax not working. How to fix it?

Harrix
  • 547
  • 3
  • 8
  • 17

2 Answers2

16

Some browsers implement strong security measures to prevent downloaded webpages from accessing arbitrary files on the file system.

Switch to a browser with weaker security (I think Firefox permits access to local files via XHR) or stop trying to run a website without HTTP.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    Also with chrome with the following command line :`chrome --allow-file-access-from-files` – pdem Feb 16 '17 at 10:31
9

This is a known problem with Chrome, if you are checking on it. Use XAMPP to run a local webserver, and test your ajax call.

Check this ticket: https://code.google.com/p/chromium/issues/detail?id=40787

Bijoy Anupam
  • 567
  • 1
  • 5
  • 12
  • 4
    Even faster, use Python (of course). In the terminal: `cd /path/to/project/folder` then `> python -m SimpleHTTPServer 8080` Use http://127.0.0.1:8080/ or a variation your system may desire. (OSX, Py 2.7x) – Marc Jul 01 '15 at 19:00
  • 2
    Or you could use node.js. > npm install -g http-server > cd /path/to/project/folder > http-server – Mark Sep 01 '15 at 20:44