JSONP is a method for sending JSON data without worrying about cross-domain issues.
It does not use the XMLHttpRequest object, but the script tag instead.
Requesting an external script from another domain does not have cross-domain policy problems.
It contains a static method which receives two parameters: an uri and a callbackName
So this methods considers two modalities:
- The first one is when an external callback name is provided.
- The second one is when no callback name is provided.
The method creates a script element first
Then, if a callback name is provided, it executes:
and does not return anything.
Else, if a callback name is provided, it executes:
The very interesting part here is the creation of a Promise object, which will be returned at method completion.
A Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
A function that is passed with the arguments resolve and reject to the Promise contructor is called executor. The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise, respectively.
In the invokeJsonp method, the executor creates a static method named danJsonpCallback inside DanJsonp class, by using Object.assign function.
This static method (DanJsonp.danJsonpCallback) will be invoked at the end of API execution, and only then it will “resolve” the promise, so to make the JSON data available to client.
In order to do that, a query parameter
finalAddress += separator + "callback=DanJsonp.danJsonpCallback"; is concatenated to the final uri, and the script element is appended to the document body.
Let’s consider a simple PHP/Apache server, which provides a simple API, and is running on http://localhost/php-jsonp/getJsonpData.php:
To get the simple JSON object provided by the PHP/Apache server, by using DanJsonp class, the client should simply invoke: