In this John Resig article, he’s is dealing with a dictionary-sized list of words with javascript, and he’s loading the content via ajax from a CDN.
The words are loaded in with newlines separating the words. Then he says cross domain fails:
There’s a problem, though: We can’t load our dictionary from a CDN!
Since the CDN is located on another server (or on another sub-domain,
as is the case here) we’re at the mercy of the browser’s cross-origin
policy prohibiting those types of requests. All is not lost though –
with a simple tweak to the dictionary file we can load it across
domains.First, we replace all endlines in the dictionary file with a space.
Second, we wrap the entire line with a JSONP statement. Thus the final
result looks something like this:dictLoaded(‘aah aahed aahing aahs aal… zyzzyvas zzz’);
This allows us to do an Ajax request for the file and have it work as
would expected it to – while still benefiting from all the caching and
compression provided by the browser.
So, if I’m reading this correctly, simply adding his method dictLoaded('original content') around the original content alone causes the ajax request to not fail.
Is that (turning it into a function + param) really all it takes? and why does JSONP solve the problem of cross domain access restriction?
the
<script>tags can load any JS file from anywhere (even cross domain). The nice thing that comes with it is that the code inside that script is also executed, therefore, a method of bypassing cross-domain restrictions.The problem is, when the code gets executed, it’s executed in the global scope. so having this code:
will create a
testvariable in the global scope.To mitigate this, you use enclose the reply in a function. This is the “P” in “JSONP” which means “padding”. This encloses your reply in a function call.
So if your foreign script has:
It calls
myFunctionand passes an object withtestkey which has valuefoo. The receiving function would look like:Now we have successfully bypassed the cross-domain restriction. The essential parts needed are: