The first time I heard about JSONP was when I recieved a technical assessment for a high end company.
When I saw it, I immediately thought: what is it? why we use it? how does it work? and how do I use JSONP in my project.
So here I will share the answer to all those questions in one place!
What is JSONP?
JSONP (JSON with Padding) is a javascript object notation it´s used to load data from the server using a script tag <script>
rather than XMLHttpRequest.
Why we use it?
The short answer is that it´s used to avoid Cross-Origin-Resource-Policy issues.
While corss-domain policy blocks accesssing files, it allows accessing scripts from another domain. JSONP uses this to access data through a script tag.
To achieve that, JSONP objects come wrapped in a callback function.
//JSON Example
{"Name": "Foo", "Id": 1234, "Rank": 7};
//JSONP Example - In this you can call a function
functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});
How does it work?
The client (typically JavaScript) must provide a callback function to which the data is later transferred, along with any other data the client wants to send.
The data transfer is called up on the client by formulating a script call. The URL of the web service on the server is specified, supplemented by the name of the callback function. The finished "script" tag must then be injected into the DOM (Domain Object Model). This process is called "script tag injection" and triggers the data transfer.
The web service on the server side takes the data, extracts the name of the callback function and uses it to bracket the server data with an appropriate function call when it is sent back .
The browser receives the server response back in the form of a script and immediately begins executing the script. Since the script consists of a function call, the "callback" function is called and this receives the data as a parameter.
How do I use JSONP in my project?
Javascript:
async () => {
const jsonpCallback = "<CALLBACK_FUNCTION_NAME>";
const response = await fetchJsonp(`<API_URL>`, {
jsonpCallback,
});
const data = await response.json();
return data;
}
Finally,
I hope you found this article helpful,
Top comments (0)