Most front-end developers consume JSON at some point. It has become commonplace nowadays to fetch data from a cross-domain site and present that data in your page. JSON is lightweight, easy to consume and one of the best things to come along in a while.
Another one of the best things to come along has been this:
jQuery makes fetching JSON trivial. And there ain’t nothin’ wrong with that. But it’s not a bad idea to have a solid understanding of exactly what is going on under the hood.
Now in the real world, your remote script would likely be produced by an API that supports JSONP. In these cases you have probably seen the URL of JSONP call look something like this:
This is a more sophisticated approach and will be covered in Part II. For now, however, we will keep things very simple. In order to do so, we have to have an agreement between our JSON file and our web page. Our web page has a function expression that makes that function available, and the JSON file knows to call that function.
First, let’s take a look at our JSON file.
Example # 1
name: 'R Jones',
name: 'K Frost',
name: 'J Sommers',
Example # 2
var script = document.createElement('script');
script.src = 'data.js';
In Example # 2, we have the markup for our web page. Now there are two things happening here:
2) After the function declaration, we dynamically append a script to the head of the document. Now if you take a close look at the ‘src’ attribute of our script, you’ll see that it is ‘data.js’
Putting the pieces together
Now that we have the details laid out, let’s walk through the sequence of events:
- The page loads, and the function declaration for jsonpCallback() is evaluated
- jsonpCallback() now exists and can be called
- We dynamically append a script tag to the page
- The URL for this new script tag is data.js
- data.js is loaded and the code inside of it executed
- data.js calls the function jsonpCallback(), and passes it the array of data
- jsonpCallback() receives the data passed to it and we inspect it in the console
Again, this is an extremely rudimentary example. The focus here was to illustrate the core concepts in play: dynamic script injection and passing data to a function. In Part II, we will look at a more dynamic approach to JSONP.
Helpful Links for JSONP