Introduction to JSONP
In order to get around the same origin policy, we will be using JSONP, which is JSON with Padding. One exception under the same origin policy is the <script>
tag so scripts can be passed across domains. JSONP uses this exception in order to pass data across domains as a script by adding padding to make the JSON object look like a script. In JavaScript, when a function with a parameter is invoked, we call the function and add a parameter. With JSONP, we pass the JSON feed as a parameter to a function; thereby, we pad our object into a function callback. This function into which the JSON feed has been padded has to be used on the client-side to retrieve the JSON feed. Let's take a quick look at a JSONP example.
In this example, we are padding the students
object into the myCallback
function and we have to reuse the myCallback
function in order to retrieve the students
object. Now that we understand how JSONP works, let's use Reddit's JSON API to fetch the data. We...