Introduction
JSONP (JSON with padding) is a method for making asynchronous requests in different domains, it is commonly used for invoking RESTful Services. JSONP is conceived because of the lack of AJAX for performing requests to resources that are in different domain. The same origin policy prevents that AJAX from being used across domain. A web page which is placed under davidsblog.eu can only access (through AJAX) to data which is under the domain davidsblog.eu and in the same port (in this case the port 80).
JSON
For understanding JSONP, the first requirement is to understand JSON. JSON (JavaScript Object Notation) is a lightweight data interchange format. This format is copied from the way for representing associative arrays (objects) in JavaScript.
This is a JSON which represents a person with three properties: name, age and sex.
{
"name" : "John"
"age" : 23,
"sex": "MALE"
}
In JavaScript this type of structures can be accessed in two ways:
var name = json["name"];
var name = json.name;
Once JSON is understood, JSONP format is just “function(json)”, a function whose unique parameter is a JSON. Example:
processPerson({ "name" : "John", "age" : 23, "sex": "MALE" });
Yes, it is not too complicated at all.
How can we do a JSONP call?
We have to include the URL of the service in a <script> HTML tag:
Continue reading →