JSONP a way to AJAX request across domains

Datetime:2016-08-22 23:49:31         Topic: Ajax  JSONP          Share        Original >>
Here to See The Original Article!!!


If you try to request to other domain different from that comes the request, exist a Policy for browsers that not allow you to do this. There are two main techniques to do this: JSONP or CORS . This example that I want to share is about how to use JSONP AJAX request.


We were trying to integrate with a service provider (SP) that perfectly complements ours to show it to our customers as an extra and to obtain an extra benefit, extending the final package. These SPs have their own public webservice to make the requests and get the necessary information, GREAT!!, half work done .

Let's do AJAX asynchronous requests and so we do not overload the page that allready takes enough. And so it began headache Buildin the JSON for the request, done! Do AJAX request with JQuery, done! There is no JSON in return, but open the Fiddler and surprise exist response!!, If I can see the response, why is not in my succes function?

I learn about Same-origin policy.

Google this, google that and finally build my JS to finish my task, and now I share a simple example.

Using the code

With the following code you will be able to obtain a JSON response from other domain that allow callback parameter.

If you need to request with another JSON just add to the data parameter as I show commented in thesample file.

        url: URL,
        type: "GET",
        jsonpCallback: "callback",
        contentType: "application/javascript",
        dataType: "JSONP",
        beforeSend: function () {
            //Do your stuff before send, ussually a loading image.
        error: function () {
            //Control the error.
        success: function (data) {
            //Parse the data or do whatever you need.


For JSONP applications to work, they need to be able to specify a callback parameter. You can specify a callback parameter by appending ?callback=[function_name], where [function_name] represents the Javascript function name to send the JSON object to. In AJAX request you must set it in JsonCallback.

Example calling:


The response:

callback({"Habana": "Gropius"});




About List