0

I'm trying to figure out AJAX through jQuery and I'm having a bit of trouble understanding something.

Using this tutorial at W3Schools, I'm trying something that I think should be pretty simple: load some text from a .txt file that's in the same directory as the .html file into a div on a button click.

Here's the directory tree:

➜  jquery_ex tree                                                                                       
.                                                                                                       
├── demo_test.txt
└── index.html

and here's the HTML/JS:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $("button").click(function(){
                $("#div1").load("file:///Users/Nerdenator/Workspace/jquery_ex/demo_test.txt",
                    function(responseTxt, statusTxt, xhr){
                        if(statusTxt == "success")
                            alert("External content loaded successfully!");
                        if(statusTxt == "error")
                            alert("Error: " + xhr.status + ": " + xhr.statusText);
                    });
                });
            });
        </script>
    </head>
    <body>
        <div id="div1">
            <h2>Let jQuery AJAX Change This Text</h2>
        </div>
        <button>Get external content</button>
    </body>
</html>  

The .html loads into a page with the url file:///Users/Nerdenator/Workspace/jquery_ex/index.html, as expected. However, on the button click, I get a 404 error alert, and the following appears in the JS console in Chrome:

jquery.min.js:4 XMLHttpRequest cannot load file:///Users/Nerdenator/Workspace/jquery_ex/demo_test.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

I'm a bit confused here; how is a request for data on the same machine in the same folder as the calling page a CORS request?

nerdenator
  • 1,265
  • 2
  • 18
  • 35
  • 2
    You can't access the file system like that with JavaScript. It's a big security no-no. – John Conde Aug 20 '16 at 14:01
  • @nerdenator See also [How to print all the txt files inside a folder using java script](http://stackoverflow.com/questions/37634049/how-to-print-all-the-txt-files-inside-a-folder-using-java-script/) – guest271314 Aug 20 '16 at 14:29

1 Answers1

0

I think url in localhost 127.0.0.1/folder name/demo_test.txt or demo_test.txt

sajjad
  • 626
  • 1
  • 7
  • 25