JSONP -- Solve ajax cross-origin problem, jsonp -- ajax cross-Origin

Source: Internet
Author: User

JSONP -- Solve ajax cross-origin problem, jsonp -- ajax cross-Origin
JSON and JSONP

What is the relationship between JSONP and JSON?

JSON (JavaScript Object Notation) is a lightweight data exchange format. You should have a good understanding of JSON. If you are not very clear about JSON, you can go to json.org to understand it easily.

  JSONP is the alias of JSON with Padding. It is an unofficial protocol that allows the server to integrate Script tags to return to the client and implement cross-origin access through javascript callback (this is only a simple implementation form of JSONP). -- Source: Baidu

JSONP is likeJSON + PaddingThe same is true for Padding.Fill). Let's take a look at the following small example and then introduce it in detail.

Simple Principle of cross-Origin

The definition is not quite clear. First, let's do a simple and easy-to-understand test manually. Create a new Asp.net web program, and upload the sample.html webpage and a test. js file. The Code is as follows:

Sample.html code:

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">2 

Code for test. js:

1 alert("success");

After logging on to sample.html, a message box such as "success" appears to be displayed. This does not seem to indicate anything. How can this problem be solved? Well, now we simulate A non-same-source environment. Didn't we create A Web program with Visual Studio just now (here we call it program ), now we open a new Visual Studio and create a new Web program (Program B. the js file is removed from program A and copied to program B. After both programs run, Visual Studio starts the built-in server. Assume that program A is localhost: 20001, and program B is localhost: 20002, this simulates a non-same source environment (although the domain name is the same but the port number is different, so it is not the same source ).

OK ,we need to change the code in sample.html. Because the test. js file is in program B, the url is changed to localhost: 20002.

Sample.html code:

1 <script type="text/javascript" src="http://localhost:20002/test.js"></script>

Keep the running status of the AB Web programs. When you refresh localhost: 20001/sample.html again, the "success" dialog box is displayed as before. Yes, access to the non-same-source localhost: 20002/test. js is a remote service. At this point, we believe that you should have understood how cross-origin access works.

<Script> the src attribute of a tag is not restricted by the same-source policy. Therefore, you can obtain and execute scripts on any server.

Implementation Mode of JSONP -- CallBack

The small example just now explains the principle of cross-origin. Let's go back and look at the definition description of JSONP to illustrate the form of javascript callback. Let's modify the code and implement the javascript callback form of JSONP.

Part of sample code in program:

1 <script type = "text/javascript">
2 // callback function
3 function callback (data ){
4 alert (data. message );
5}
6 </script>
7 <script type = "text/javascript" src = "http: // localhost: 20002/test. js"> </script>

Code of test. js in program B:

1 // call the callback function and transmit the data in json format to complete the callback.
2 callback ({message: "success "});

This is actually the simple implementation mode of JSONP, or the prototype of JSONP:Create a callback function, call this function on the remote service, and pass the JSON data as a parameter to complete the callback..

Fill JSON data into the callback functionThis is the meaning of JSON + Padding of JSONP.

In general, we hope that the script tag can be dynamically called, rather than being executed without waiting for page display because it is fixed in html. We can dynamically create a script tag through javascript, so that we can flexibly call remote services.

Part of sample code in program:

1 <script type = "text/javascript">
2 function callback (data ){
3 alert (data. message );
4}
5 // Add the <script> label
6 function addScriptTag (src ){
7 var script = document. createElement ('script ');
8 script. setAttribute ("type", "text/javascript ");
9 script. src = src;
10 document. body. appendChild (script );
11}
12
13 window. onload = function (){
14 addScriptTag ("http: // localhost: 20002/test. js ");
15}
16 </script>

The test. js Code of program B remains unchanged. Do we need to execute the program again. If you want to call another remote service, you only need to add the addScriptTag method and input the src value of the remote service. The following explains why to add the addScriptTag Method to the window. in the onload method, the reason is that the addScriptTag method contains a document. body. appendChild (script); the script tag is added to the body, because the javascript code we write is in the head tag, document. the body has not been initialized, so we need to use window. the onload method first initializes the page to avoid errors.

The above example is the simplest implementation model of JSONP, but it is not a real JSONP service. Let's take a look at the real JSONP service is how, such as Google ajax search interface: http://ajax.googleapis.com/ajax/services/search/web? V= 1.0 & q =? & Callback =?

Q =? This question mark indicates the content you want to search for. The most important is the second callback =? This is the name of the callback function, that is, the name of the callback function defined on the client is sent to the server, the server will return the method with the callback function name you defined, and pass the obtained json data into this method to complete the callback. It's a bit cool. Let's take a look at the implementation code:

1 <script type = "text/javascript">
2 // Add the <script> label
3 function addScriptTag (src) {4 var script = document. createElement ('script'); 5 script. setAttribute ("type", "text/javascript"); 6 script. src = src; 7 document. body. appendChild (script); 8} 9

10 window. onload = function () {11 // search for apple and pass the custom callback function name result to the callback parameter.
12 addScriptTag ("http://ajax.googleapis.com/ajax/services/search/web? V = 1.0 & q = apple & callback = result "); 13
14} 15 // custom callback function result
16 function result (data) {17 // we can obtain the url data in the first record of the apple search result.
18 alert (data. responseData. results [0]. unescapedUrl); 19} 20 </script>

There are many other JSONP services like this (the following information comes from the use of JSONP for cross-origin communication, Part 1: quickly build a powerful mashup with JSONP and jQuery ):

Digg API: toutiao news from Digg:

Http://services.digg.com/stories/top? Appkey = http % 3A % 2F % 2Fmashup.com & type = javascript & callback =?

Geonames API: Location Information of the zip code:

Http://www.geonames.org/postalCodeLookupJSON? Postalcode = 10504 & country = US & callback =?

Flickr jsonp api: Load pictures of the latest Cat:

Http://api.flickr.com/services/feeds/photos_public.gne? Tags = cat & tagmode = any & format = json & jsoncallback =?

Yahoo Local Search API: Search for Pisa in a region with a zip code of 10504:

Http://local.yahooapis.com/LocalSearchService/V3/localSearch? Appid = YahooDemo & query = pizza & zip = 10504 & results = 2 & output = json & callback =?

Next we will create a simple remote service to implement the same JSONP service as above. We still use Web program A and program B for demonstration. This time we create A MyService. ashx file on program B.

MyService. ashx code of program B:

1 public class MyService: IHttpHandler
2 {
3 public void ProcessRequest (HttpContext context)
4 {
5 // get the callback function name
6 string callback = context. Request. QueryString ["callback"];
7 // json data
8 string json = "{\" name \ ": \" chopper \ ", \" sex \ ": \" man \"}";
9
10 context. Response. ContentType = "application/json ";
11 // output: callback function name (json data)
12 context. Response. Write (callback + "(" + json + ")");
13}
14
15 public bool IsReusable
16 {
17 get
18 {
19 return false;
20}
21}
22}

Call in sample code of program:

1 <script type = "text/javascript"> 2 function addScriptTag (src) {3 var script = document. createElement ('script'); 4 script. setAttribute ("type", "text/javascript"); 5 script. src = src; 6 document. body. appendChild (script); 7} 8 9 window. onload = function () {10 // call remote service 11 addScriptTag ("http: // localhost: 20002/MyService. ashx? Callback = person "); 12 13} 14 // callback function person15 function person (data) {16 alert (data. name + "is a" + data. sex); 17} 18 </script>

This completes a basic JSONP service call. Isn't it easy? Let's take a look at how JQuery calls JSONP.

JQuery's implementation of JSONP

The jQuery framework also supports JSONP Of course, you can use the $. getJSON (url, [data], [callback]) method (For details, refer to the http://api.jquery.com/jQuery.getJSON ). Then let's modify the code of program A and use the getJSON method of jQuery to implement it (the following example does not use passing parameters to the service, so only getJSON (url, [callback]):

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript">    
$.getJSON("http://localhost:20002/MyService.ashx?callback=?",
function(data){ alert(data.name + " is a a" + data.sex); });
</script>

The results are the same. Note that a callback parameter must be added after the url so that the getJSON method will know that the service is accessed using JSONP, the question mark after callback is an internal automatically generated callback function name. You can debug this function name, for example, jQuery17207481773362960666_1332575486681.

Of course, what should we do if we want to specify our own callback function name, or if the service specifies a fixed callback function name? We can use the $. ajax Method for implementation (more parameters, see the http://api.jquery.com/jQuery.ajax for details ). Let's take a look at how to implement it:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript">    $.ajax({         url:"http://localhost:20002/MyService.ashx?callback=?",            dataType:"jsonp",         jsonpCallback:"person",         success:function(data){             alert(data.name + " is a a" + data.sex);         }    }); </script>

Yes, jsonpCallback means that we can specify our own callback method name person. The value that the remote service accepts the callback parameter is no longer the automatically generated callback name, but the person. DataType specifies that the remote service is accessed in JSOPN mode.

Using jQuery, you can easily implement JSONP for cross-origin access. Write it here for now.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.