First, talk about how JSONP is produced:
In fact, there are a lot of jsonp on the Internet, but the uniform, and foggy, for many people just contact to understand some difficulties, small not only, try to use their own way to explain the problem, see if it helps.
1, a well-known problem, Ajax directly request ordinary file There is no access to cross-domain issues, no matter you are static pages, dynamic Web pages, Web services, WCF, as long as the cross-domain requests, are not allowed;
2, but we also found that the Web page when the JS file is not affected by whether or not cross-domain impact (not only that, we also found that the "src" attribute of the label has the ability to cross-domain , such as <script>, , <iframe>);
3, so can judge, the current stage if you want to through the pure Web side (ActiveX control, Server Agent, belongs to the future of HTML5 WebSocket, etc.) access to data across domains is only one possibility, that is, on the remote server to try to load the data into the JS format of the file, For client invocation and further processing;
4, it happens that we already know that there is a kind of pure character data format called JSON can be concise description of complex data, even better is the JSON is also supported by JS native, so in the client can almost arbitrary processing of this format of data;
5, such a solution is to be seen, the Web client by the same way as the call script to invoke the cross-domain server dynamically generated JS format files (usually JSON suffix), it is obvious that the server to dynamically generate JSON files, The goal is to load the data that the client needs.
6, the client in the JSON file after the successful call, but also to obtain their own required data, the rest is to do their own needs to deal with and show that the way to get remote data looks very much like Ajax, but in fact, it is not the same.
7, in order to facilitate the use of data by the client, gradually formed an informal transport protocol, people call it Jsonp, one of the main points of the protocol is to allow users to pass a callback parameter to the server, The callback parameter is then used as the function name to wrap the JSON data when the server returns data, so that the client can customize its own function to automatically process the returned data.
If there is some ambiguity about how the callback parameter is used, there are specific examples to explain later.
Second, the JSONP client specific implementation:
No matter jquery or ExtJS, or other support JSONP framework, they do the work behind the scenes are the same, I would like to gradually explain the JSONP in the client implementation:
1. We know that even if the code in the cross-domain JS file (which is, of course, conforms to the Web Scripting Security Policy), the Web page can be executed unconditionally.
The remote server remoteserver.com root directory has a remote.js file code as follows:
Alert (' I am a remote file ');
There is a jsonp.html page code below the local server localserver.com:
<! DOCTYPE HTML public " -//W3C//DTD XHTML 1.0 transitional//en " " http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd " > " http://www.w3.org/ 1999/xhtml " > " text/javascript " src= " http:// Remoteserver.com/remote.js " ></script>
There is no doubt that the page will pop up a prompt form that shows cross-domain invocation success.
2. Now we define a function on the jsonp.html page and then pass in the data in the remote Remote.js to make the call.
The jsonp.html page code is as follows:
<! DOCTYPE HTML Public"-//W3C//DTD XHTML 1.0 transitional//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD">"http://www.w3.org/1999/xhtml">"Text/javascript">varLocalhandler =function (data) {alert ('I am a local function, can be called cross-domain remote.js file, remote JS brings the data is:'+Data.result); }; </script> <script type="Text/javascript"Src="Http://remoteserver.com/remote.js"></script>
The Remote.js file code is as follows:
Localhandler ({"result":" I am the data brought by remote JS "});
After running to view the results, the page successfully pops up the prompt window, showing that the local function was successfully cross-domain remote JS call, and also received the data from the remote JS. Happily, the goal of cross-domain remote data acquisition is basically realized, but another problem arises, how can I let remote JS know what the local function it should call called? After all, JSONP service providers have to face a lot of service objects, and these service objects are different local functions? We went on to look down.
3, smart developers are very easy to think, as long as the server provided by the JS script is dynamically generated on the line, so that callers can pass a parameter in the past to tell the service side "I want a call xxx function JS Code, please return to me", so the servers can follow the client's needs to generate JS script and response.
Look at the code for the jsonp.html page:
<! DOCTYPE HTML Public"-//W3C//DTD XHTML 1.0 transitional//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD">"http://www.w3.org/1999/xhtml">"Text/javascript">//callback function After getting the flight information query result varFlighthandler =function (data) {alert ('The result of the flight you are inquiring for is: Ticket price'+ Data.price +'Yuan,'+'remaining votes'+ Data.tickets +'of the card. '); }; //provide the URL address of the JSONP service (regardless of the type of address, the resulting return value is a piece of JavaScript code) varURL ="Http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler"; //Create a script tag, set its properties varScript = Document.createelement ('Script'); Script.setattribute ('src', URL); //Add the script tag to head, and the call startsdocument.getElementsByTagName ('Head')[0].appendchild (script); </script>
This time the code changes relatively large, no longer directly to the remote JS file to write dead, but the code to implement dynamic query, and this is the core part of the JSONP client implementation , the focus of this example is how to complete the JSONP call the whole process.
We see the URL of the call passed a code parameter, tell the server I want to check the CA1998 flight information, and the callback parameter tells the server, my local callback function is called Flighthandler, so please pass the query results into this function to call.
OK, the server is very smart, this is called Flightresult.aspx Page generated a section of this code to provide to jsonp.html (service-side implementation is not demonstrated here, and you choose the language regardless of, in the final analysis is stitching strings):
Flighthandler ({ "code""CA1998", "price"1780, "tickets " 5 });
As we can see, a JSON is passed to the Flighthandler function, which describes the basic information of the flight. Run the page, the successful pop-up prompt window, JSONP implementation of the entire process completed successfully!
4, so far, I believe you have been able to understand the JSONP of the client implementation of the principle of it? The rest is how to encapsulate the code to make it easier to interact with the user interface for multiple and repeated calls.
If you're using jquery, you want to know how jquery implements JSONP calls? The following section of jquery uses JSONP code (we still follow the example of the flight information query above, assuming that the return JSONP result is the same):
<! DOCTYPE HTML Public"-//W3C//DTD XHTML 1.0 transitional//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD"> "http://www.w3.org/1999/xhtml"> "Text/javascript"Src=jquery.min.js"></script><script type="Text/javascript">jQuery (document). Ready (function () {$.ajax ({type:"Get", Async:false, URL:"http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998", dataType: "Jsonp", Jsonp: "Callback",//pass to the request handler or page, the parameter name to get the JSONP callback function name (generally by default: callback) Jsonpcallback: "Fligh Thandler ",///Custom JSONP callback function name, default to jquery automatically generated random function name, can also write"? ", jquery will automatically process the data for yousuccess:function (JSON) {alert ('Your flight information: fare:'+ Json.price +'Yuan, the remaining votes:'+ Json.tickets +'of the card. '); }, Error:function () {alert ('fail'); } }); }); </script>
Isn't it a little strange? Why didn't I write this flighthandler function this time? And it worked! Haha, this is the credit of jquery, jquery in the processing of JSONP type of Ajax (or can not help to spit groove, although jquery also put Jsonp into Ajax, but in fact, they really are not a thing), Is it cool to automatically generate callback functions for you and take the data out for the Success property method to invoke?
5, the similarities and differences between Ajax and JSONP to do some additional explanation:
(1), Ajax and JSONP the two technologies "look" like in the way of invocation, the purpose is the same, is to request a URL, and then the data returned by the server processing, so the jquery and ext frameworks have Jsonp as a form of Ajax encapsulation;
(2), but Ajax and JSONP are actually different things in nature. The core of Ajax is to obtain non-page content through XMLHttpRequest, while the core of JSONP is dynamic add <script> tag to invoke the JS script provided by the server.
(3), so that, in fact, the difference between Ajax and JSONP is not whether cross-domain, AJAX through the service-side proxy can be implemented across domains, JSONP itself does not exclude the same domain data acquisition.
(4), there is, Jsonp is a way or non-mandatory protocol, like Ajax, it does not have to use JSON format to pass the data, if you want to, the string is OK, but this is not conducive to the use of JSONP to provide public services.
(5), in short, JSONP is not a special case of Ajax, even if the giant jquery Jsonp package into the Ajax, can not change a little!
What is JSONP?