What is JSONP?
The short answer
JSONP (JSON with Padding) is an old technique for making cross-origin requests before CORS existed. It works by loading data through a <script> tag instead of an AJAX request. The server wraps the JSON data in a function call, and the browser executes it. It is mostly a historical technique — use CORS and fetch instead.
How it works
The browser can load scripts from any origin (the same-origin policy does not block <script> tags). JSONP exploits this:
1// 1. Define a callback function2function handleData(data) {3 console.log(data.name); // "John"4}56// 2. Load a script from another origin7const script = document.createElement('script');8script.src =9 'https://api.example.com/user?callback=handleData';10document.body.appendChild(script);
The server responds with:
1handleData({ name: 'John', age: 30 });
The browser executes this like any script, which calls handleData with the data.
Why it is not used anymore
- Security risk — you are executing arbitrary code from another server. If the server is compromised, it can inject malicious code.
- Only supports GET — no POST, PUT, or DELETE
- No error handling — if the request fails, you get no error callback
- CORS exists — CORS is the standard, secure way to make cross-origin requests
Interview Tip
Explain that JSONP was a hack to bypass the same-origin policy using script tags. Show the basic mechanism (callback function + script tag). Then say it is replaced by CORS. This is a history question — keep it brief.
Why interviewers ask this
This tests if you know the history of cross-origin requests. Understanding JSONP helps you appreciate why CORS was created and why modern security mechanisms exist.
Related Web Security interview topics
Continue with nearby questions from the same topic cluster.