Reputation: 1701
This is going to be downright obvious to someone else, but for the life of me, I cannot figure it out.
I've copied the HTML from http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get
I changed one line slightly so that .get url points to the full w3schools.com url (this works just fine on their example page). This is the code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("http://www.w3schools.com/jquery/demo_test.asp",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
This code works just fine for me on the w3schools website, but when I paste it into a new file called "hi.html" on my home computer and open it up in Chrome and Firefox, it fails.
I'm copying and pasting this html directly, why does this fail?
Upvotes: 1
Views: 593
Reputation: 6680
Your web browser prevents the Ajax request from executing because of the same-origin policy (https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). Basically, when you run the script on localhost:80, you can only make Ajax requests to pages on localhost:80. W3Schools is on a different host.
The same-origin policy exists for security reasons. For example, suppose you are logged into Facebook. If the same-origin policy didn't exist, a programmer could make a malicious website that makes an Ajax request for Facebook.com and it would return with your login cookies. It could then send your login cookie to the malicious programmer. The malicious programmer could then take your login cookies and impersonate you on Facebook.
Upvotes: 3