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?