R
R
Rrooom2014-08-21 10:43:01
JavaScript
Rrooom, 2014-08-21 10:43:01

What is jsonp and how to use it?

It seems to be an old thing, but has not yet been used. What it is?
Why do browsers block just getting json by Ajax, but allow jsonp?

How and why to use it?

I looked at the examples on javascript, nothing worked - complains "this is not jsonp". Can you provide a valid example that can be tested?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill, 2014-08-21
@Rrooom

This is a technology for making a request to another domain (this is not possible through a regular XHR).
In a nutshell, this works like this:
A new script tag is added to the head of the page with src set to the request address and parameters (eg " www.example.com/?id=1&jsonp=myCallback ").
As you understand, this script will be loaded by the browser regardless of the domain we are on.
At the same time, the response side (example.com) in the body of this script will return not just JSON, but a call to the javascript function specified in the jsonp parameter (of course, we must declare this function in advance).
Sample response from example.com: myCallback({ "user": "Rrooom", "message": "test" });
This is not a bad way to get around the problem of cross domain requests, but only GET is possible.

S
Sergey, 2014-08-21
Protko @Fesor

JSONP is a hack currently used only by things like IE, which before version 10 didn't support CORS.
The problem is that the browser's security policy does not allow cross-domain XHR requests (tobish AJAX in common language). Considering that angular-based (and indeed any application on the client) applications must receive data from the REST API, and this API can be located on another server, it is quite logical that you need to come up with some way to receive this data and that it could be do it regardless of browser restrictions.
Normal guys for normal browsers came up with and use CORS(Cross-origin resource sharing), which is standardized, works well and nicely and is easily screwed into the project. But if you have declared support for IE9 or older versions, then all this will not work there and you have to sculpt jsonp again.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question