What I have learnt about JSON-P (from JSON-P VS JSON and wikipedia) is - JSON-P is invented to overcome the same origin policy of browsers and load JSON objects from another domain. There is a post on stackoverflow which shows how JSON-P calls work. There it seems, if I remove ?callback=? from the URL, the JSON-P request acts like plain JSON call and hence rejected by same origin policy. Which is proved by this live example .
Now I have another URL : https://graph.facebook.com/100001612121705.json
And I use following method to load data from it (visit here for live example):
$(document).ready(function() {
$.getJSON("https://graph.facebook.com/100001612121705", null,
function(data) {
$.each(data, function(key, val) {
alert(key + ' is ' + val);
});
});
});
Note that I am not using the ?callback? with my URL and still this request is able fetch JSON data from another domain ! Which is very surprising to me. Can anyone kindly explain why is this request not rejected by Same Origin Rule ?
It's because the HTTP-response contains this header:
Access-Control-Allow-Origin: *
The * means that any origin may retrieve the given resource via XHR (Ajax).
So, if you have a resource on your web-server, and you want to make it available via XHR regardless of origin, just add the above header to the HTTP-response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With