JavaScript JSON And JSONP Explanation

Here is explanation to clarify the concepts with JSON and JSONP side by side.

1. JSON (JavaScript Object Notation)

JSON is a minimal readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.

The two primary parts that make up JSON are keys and values.

  • Key: A key is always a string enclosed in quotation marks.
  • Value: A value can be a string, number, boolean expression, array, or object.
  • Key/Value Pair: A key value pair follows a specific syntax, with the key followed by a colon followed by the value. Key/value pairs are comma separated.

2. JSONP stands for JSON with Padding

Normally, XMLHttpRequest doesn’t permit cross-domain data-exchange directly (one needs to go through a server MUST under the same domain).However, below script tag can access data from a domain different than from the origin-domain.

JSONP is used to overcome the XMLHttpRequest Same-origin policy. It works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is the JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

JSONP has nothing to do with Ajax since it does not use XMLHttpRequest. Instead it dynamically inserts script tag into a webpage. So instead of using XMLHttpRequest, script HTML tags will be used, the ones you usually use to load js files, in order for js to get data from another domain.

Thing is – turns out script HTML tags can be used in a fashion similar to XMLHttpRequest. Check this out:

You will end up with a script segment that looks like this after it loads the data:

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better(and it is):

Notice the fnCallback function over there? So – when JSONP server receives your request and finds callback parameter – instead of returning plain js array it’ll return this:

See where the profit is: now we get automatic callback fnCallback that’ll be triggered once we get the data. That’s all JSONP works: call callback function and create script tags .

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

Basic JavaScript example (simple Twitter feed using JSONP)

Basic jQuery example (simple Twitter feed using JSONP)

Resource: Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA