Jsonp difference and simple receive request (cross domain)

I need to send (and receive) certain data to the server using jQuery and JSON. It still works, but not a cross-domain, and it should be a cross-domain.

I looked at how to solve this and found JSONP. As far as I see, using JSONP, I have to send a callback and data using GET (JQuery allows you to use the "POST" method as a method, but when I check the web traffic, I see that it actually sends GET and each parameter as parameter).

JSONP also requires changes on the server, because they are waiting for a POST request with JSON data, and they need to implement something to handle the JSONP GET request.

So, I am wondering what is the difference between this and sending data as key value parameters in a GET request?

Is there any difference in the possibility of using a callback? Or what exactly?

Sorry, a little lost ... thanks in advance

+4
source share
2 answers

JSONP is not a form submission. This is a way to tell the server using a GET request how to create content for the script tag. The returned data represents a payload of JavaScript (and not just JSON!) With a callback function call that you (by convention) reference in the GET request.

JSONP works because it is a hack that does not use AJAX. This is not AJAX, and you should not confuse it, because it does not use XMLHttpRequest at any time to send data. This is exactly what happens around the same origin policy.

Depending on the browsers you need to support, you can use server-side Cross-Origin resource sharing headers, which allows you to use regular AJAX calls through trusted domains. Most browsers (IE8, Firefox 3.5+, etc.) will support CORS.

Another solution that you can use if you do not want to use CORS or JSONP is to write a PHP script or Java servlet that will act as a proxy server. It is as simple as opening a new connection from a script, copying all incoming parameters from your AJAX code to the request, and then discarding the response at the end of your script.

+5
source

I found an answer that worked for me with a cross-domain problem and JSON (and not JSONP). I just used:

header('Access-Control-Allow-Origin: *'); 

inside my json file (file.php) and called it like this:

 var serviceURL = 'http://your-domain.com/your/json/location.php' $.getJSON(serviceURL,function (data) { var entries = data; //do your stuff here using your entries in json }); 

BTW: This is a receiving process, not a sending.

+2
source

Source: https://habr.com/ru/post/1393972/


All Articles