Reputation: 35276
This is an answer about accessing resource cross-domain:
The XHR is constrained by cross-domain rules; to use JSONP you need to add a script element:
function func_callbk()
{
console.log(arguments);
}
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'http://abhishekprakash.com/script/example.json?callback=func_callbk';
var h = document.getElementsByTagName('script')[0];
h.parentNode.insertBefore(s, h);
As pointed out by Ian in the comments, the proper response of your server should be something like this:
func_callbk('hello world')
Questions:
s.src = 'http://abhishekprakash.com/script/example.json?callback=func_callbk';
is that correct?func_callbk('hello world')
when the above resource is accessed? Upvotes: 0
Views: 1039
Reputation: 707158
Browsers will allow <script>
tags to refer to cross domain resources (along with a few other tags such as <img>
and <iframe>
and a few others, but will not allow ajax calls to reference cross domain servers without specific permissions being granted.
JSONP uses this capability given to <script>
tags in order to work-around the cross domain issue. It requires the destination server to support the JSONP way of doing things so the server must cooperate. The results coming back from the JSONP call must actually be a script and it must call the function name reqeusted in the JSONP request URL and pass the desired data to that script.
You might want to read this article describing how JSONP works.
And this MDN same-origin article about the details of what is and isn't allowed for cross domain access.
If you're willing to require a newer browser and set up things appropriately on your server, you can use Cross Origin Resource Sharing. Info here and here.
Upvotes: 1