What is JSONP?

What is JSONP?

Let us talk about how JSONP is generated:

In fact, the Internet has a lot to explain about JSONP, but stereotyped, and foggy, for many people new to speaking difficult to interpret, with their own way to explain this issue to see if that helps.

1, a well-known problem, Ajax direct cross-domain request without access to a common file problems, no matter you are static pages, dynamic web pages, web services, WCF, as long as the cross-domain requests, will be allowed.

2, but we also found that the impact of cross-domain is not whether you call js file on a Web page (Not only that, we also found that those who have the "src" attribute of the tags have the ability to cross-domain, such as <\ script> , <\ img>, <\ iframe>).

3, so you can judge by the current stage if you want to end the pure web (ActiveX Controls, proxy server, the future belongs to HTML5 is not the Websocket etc.) accessing data across domains is only one possible, that is to try on a remote server js file loaded into the data format, the client calls and for further processing.

4, as it happens we already know there is something called pure character JSON data format concise description of complex data, even better is also js native JSON support, so this format of the data processing on the client side can be almost arbitrary.

5, with such solutions ready to come up, web client by calling the script exactly the same way, to call js file format dynamically generated on cross-domain server (generally JSON suffix), it is obvious why the server to dynamically generate JSON document, the purpose is to load data into the client needs.

6, the client after the call to the success of the JSON file, also obtained data they need, the rest is processed in accordance with their needs and show that this way of remote data acquisition looks very much like AJAX, but in fact not the same.

7, in order to facilitate the use of the client data, gradually formed an informal transport protocol, it JSONP call it, a point of the protocol is to allow users to pass a callback parameter to the server, the server would then return the data when the callback function name as a parameter to wrap the JSON data so that clients can freely customize their function to automatically process the returned data.

If you how to use some vague parameters for a callback, then we will have specific examples to explain later.

JSONP client specific implementation:

Regardless of jQuery Ye Hao, extjs worth mentioning, or other support jsonp framework of the work done behind the scenes they are the same, Let me explain step by step to achieve the client's jsonp:

1, we know that, even if cross-domain file js code (of course, means a web scripting security policy), web pages can also be executed unconditionally.

There are at the root of a remote server remoteserver.com remote.js file code is as follows:

alert('我是远程文件');

There under a local server localserver.com jsonp.html page code is as follows:

  1.  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2.  
    <htmlxmlns="http://www.w3.org/1999/xhtml">
  3.  
    <head>
  4.  
    <title> </title>
  5.  
    <scripttype="text/javascript"src="http://remoteserver.com/remote.js"> </script>
  6.  
    </head>
  7.  
    <body>
  8.  
     
  9.  
    </body>
  10.  
    </html>

Undoubtedly, the page will pop up a prompt window, showing the success of cross-domain calls.

2. Now we define a function, and then call in the incoming data in remote remote.js jsonp.html page.

jsonp.html page code is as follows:

  1.  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2.  
    <htmlxmlns="http://www.w3.org/1999/xhtml">
  3.  
    <head>
  4.  
    <title> </title>
  5.  
    <scripttype="text/javascript">
  6.  
    var localHandler = function(data){
  7.  
    Alert ( 'I am a local function, can be cross-domain remote.js file calls, remote data is brought js:' + data.result);
  8.  
    };
  9.  
    </script>
  10.  
    <scripttype="text/javascript"src="http://remoteserver.com/remote.js"> </script>
  11.  
    </head>
  12.  
    <body>
  13.  
     
  14.  
    </body>
  15.  
    </html>

remote.js document code is as follows:

localHandler({"result":"我是远程js带来的数据"});

After running View Results, page successfully prompted window, displays the local function is a cross-domain remote js call succeeds, and also received the data from a remote js brings.
Very pleased, the purpose of cross-domain remote access to data basically achieved, but it is a problem, how do I let the remote js function it should call the local know What is the name of it? After all, the service is jsonp who have to face a lot of clients, and these serve their local functions are not the same ah? We then look down.

3, smart developers can easily think of, as long as js script server provides is dynamically generated on the line chanting, so the caller can pass a parameter in the past to tell the server "I want some call js code XXX function, you return to me ", so the server can in accordance with the needs of the client to generate js script and responded to.

Look at the code jsonp.html page:

  1.  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2.  
    <htmlxmlns="http://www.w3.org/1999/xhtml">
  3.  
    <head>
  4.  
    <title> </title>
  5.  
    <scripttype="text/javascript">
  6.  
    // get the flight information query results callback function
  7.  
    var flightHandler = function(data){
  8.  
    Alert ( 'flights on the results of your query is: Fares' + data.price + 'Yuan' + 'than votes' + data.tickets + '. Zhang' );
  9.  
    };
  10.  
    // jsonp provide services url address (no matter what type of address, and ultimately generate the return value is a piece of javascript code)
  11.  
    var url = "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler" ;
  12.  
    // Create the script tag, set its properties
  13.  
    var script = document.createElement( 'script' );
  14.  
    script.setAttribute( 'src' , url);
  15.  
    // The script tag to the head, this time calling start
  16.  
    document.getElementsByTagName( 'head' )[ 0 ].appendChild(script);
  17.  
    </script>
  18.  
    </head>
  19.  
    <body>
  20.  
     
  21.  
    </body>
  22.  
    </html>

This code change is relatively large, no longer write directly to the remote js file dead, but Coding dynamic query, and this is what jsonp client implementation of the core part, the focus in this case is how to do it is to call jsonp the whole process.
We see the url called by a code parameter passed, I want to tell the server to check the time information is CA1998 flight, and callback parameter tells the server to my local callback function called flightHandler, so please pass this function the query results the call.
OK, the server is very clever, this is called flightResult.aspx page generation for a while this code to jsonp.html

(Implement the service here is not the end of the presentation, and your choice of language, in the final analysis is the string concatenation):

  1.  
    flightHandler({
  2.  
    "code": "CA1998",
  3.  
    "price": 1780,
  4.  
    "tickets": 5
  5.  
    });

4. Up to this point, I believe that you have been able to understand jsonp client implementation principle, right? The rest is about how the code package, in order to interact with the user interface, enabling multiple and repeated calls

JQuery how to achieve jsonp call?

  1.  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2.  
    <htmlxmlns="http://www.w3.org/1999/xhtml" >
  3.  
    <head>
  4.  
    <title>Untitled Page </title>
  5.  
    <scripttype="text/javascript"src=jquery.min.js"> </script>
  6.  
    <scripttype="text/javascript">
  7.  
    jQuery( document).ready( function(){
  8.  
    $.ajax({
  9.  
    type: "get" ,
  10.  
    async: false ,
  11.  
    url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998" ,
  12.  
    dataType: "jsonp" ,
  13.  
    jsonp : "the callback" , // passed to the request handler, or pages, to obtain the name of the callback function parameter name jsonp (typically default: callback)
  14.  
    jsonpCallback: "flightHandler" , "?" // JSONP callback function name of the custom default random function names are automatically generated for jQuery, you can also write, jQuery will automatically process the data for you
  15.  
    success: function(json){
  16.  
    Alert ( 'queries to your flight information: Tickets:' + json.price + 'dollars, vote:' + json.tickets + '. Zhang' );
  17.  
    },
  18.  
    error: function(){
  19.  
    alert( 'fail' );
  20.  
    }
  21.  
    });
  22.  
    });
  23.  
    </script>
  24.  
    </head>
  25.  
    <body>
  26.  
    </body>
  27.  
    </html>

Is not it strange? Why this time I did not write flightHandler this function? And surprisingly successful operation!
This is a credit to the jQuery, jquery when dealing jsonp type of ajax (, although the jsonp jquery also included in the ajax, but in fact they are really not the same thing children), automatic callback and help you generate the data taken out property method to call for success, it is not so cool it?
supplement

Here to do some additional explanation for the similarities and differences ajax and jsonp:

. 1, and jsonp ajax on these two technologies is called "look" like an object, too, is a request url, then the server returns the data is processed, and therefore jquery jsonp regarded as a frame. Ext ajax one form of package.

2, but the ajax and jsonp actually something different nature. Ajax is to acquire non-core content on this page by XmlHttpRequest, while the core is dynamically added jsonp

Guess you like

Origin www.cnblogs.com/hanguidong/p/11041337.html