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.getJSON()
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.
The big advantage of JSONP is that it allows data to be retrieved from any URL on the planet with no concern for the kind of cross-domain limitations of AJAX. So this means that we are taking advantage of one of the older features of the JavaScript language: the ability to inject a remote script into our page. In a nutshell, JSONP is accomplished via dynamic script injection. In other words, you create a script tag, set the ‘src’ attribute to be any script you like, and that script calls a function in your page, passing it some data.
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:
http://www.somedomain.com?callback=
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
jsonpCallback([ { name: 'R Jones', accountNumber: 010203 }, { name: 'K Frost', accountNumber: 242526 }, { name: 'J Sommers', accountNumber: 717273 } ]); |
Example # 1 is our JSON file. It is really just a JavaScript file. It consists of one function call: jsonpCallback(). The sole argument to this function call is an array of objects. Each object has two properties: ‘name’ and ‘accountNumber’.
We’ll come back to this file shortly. For now, it’s just important to focus on the fact that this is simply a JavaScript file that makes a function call, and passes an array to that function.
Example # 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JSONP With Only Native JavaScript</title> </head> <body> <h1> Please open your JavaScript console </h1> <script> function jsonpCallback(data){ console.dir(data); }; var script = document.createElement('script'); script.src = 'data.js'; document.getElementsByTagName('head')[0].appendChild(script); </script> </body> </html> |
In Example # 2, we have the markup for our web page. Now there are two things happening here:
1) The function declaration jsonpCallback() might look familiar to you. This is the function that is called from our JavaScript file ‘data.js’. Notice that this function takes one argument: ‘data’. So it expects to receive some data. Inside the function we assume that the data came through and we inspect it in the console.
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.
Here is a link to the working example for this argument: http://examples.kevinchisholm.com/javascript/jsonp/example-1/
Summary
In this article we learned how to implement JSONP using only native JavaScript. We discussed how the script that we dynamically inject into the page calls a function, passing data into the function that it calls.