JSONP means JSON with Padding. A server wraps normal JSON in a JavaScript function call so a <script> tag can load it from another site.
Browsers allow cross-origin scripts, but not cross-origin fetch / XHR without CORS. JSONP used that script loophole before CORS was common. Today it is legacy—learn it to read old APIs, then prefer plain JSON with CORS.
Quick rule.
New APIs → JSON + CORS + fetch. Old callback APIs → JSONP. Never treat a JSONP response as something JSON.parse can eat whole.
Flow
How It Works
Define a global callback, e.g. handleData.
Inject a <script> whose src includes ?callback=handleData.
The server returns padded JavaScript: handleData({…}).
The browser runs that script; your callback receives the object.
Compare
JSON vs JSONP
The data inside can be the same. The wrapper decides whether JSON.parse works.
Plain JSON
JSON
{
"name": "Ada",
"id": 1
}
Valid for JSON.parse and for JSON Schema validation of the document.
JSONP (padded)
JavaScript
handleData({
"name": "Ada",
"id": 1
});
Not JSON text. It is a function call. JSON.parse throws.
Modern
Prefer CORS + JSON
GET onlyScript tags cannot POST / PUT / DELETE.
No headersYou cannot send Authorization or custom headers on a script load.
Runs as codeTrust the host completely—or do not use JSONP.
CORS + fetchServer sends JSON; browser reads data, not executable padding.
JSON
// Preferred today (when the API allows CORS)
const res = await fetch("https://api.example.com/user");
const data = await res.json(); // plain JSON
console.log(data.name);
Code
Examples
Use View Output for a quick result, or Try It Yourself to edit and run in the browser.
Example 1 — Callback Padding
What the server “pads” around the JSON—your function runs with the object.
JSON
function handleData(data) {
console.log(data.name);
console.log(data.id);
}
// Simulated JSONP response from the server:
handleData({ name: "Ada", id: 1 });
Padding adds handleData(…);, which breaks JSON.parse.
JSONP delivers data by running script, not by parsing JSON text.
Frequently Asked Questions
JSON with Padding. The server wraps a JSON value in a JavaScript function call so a <script> tag can load it from another origin.
No for new work. Use CORS with fetch (or XMLHttpRequest) and plain JSON. Learn JSONP mainly for legacy APIs.
The browser runs the remote response as script on your page. A bad or compromised endpoint can run any JavaScript. Only use trusted hosts.
No. Padding turns the text into JavaScript (a function call), not strict JSON. JSON.parse throws unless you strip the padding yourself—which is not how JSONP is meant to work.