On the solution of JSONP Ajax Cross-domain problem _ajax related

Source: Internet
Author: User
Tags json script tag zip port number

JSON and JSONP

Jsonp and JSON like, what's the connection between them?

JSON (JavaScript Object notation) is a lightweight data interchange format. For the JSON everyone should be very familiar with it, not very clear friends can go to the json.org on the understanding, easy to understand.

Jsonp is the Lou of JSON with padding. It is an unofficial protocol that allows the integration of script tags on the server side to return to the client, enabling Cross-domain access through JavaScript callback (this is just a jsonp simple implementation).

Jsonp is like json+padding (padding here we are filled), let's take a look at the small examples below and then introduce them in detail.

Homology policy

Why is there such a mistake? This is because all JavaScript-enabled browsers use the same security policy as the homology policy. Look at Baidu's explanation:

Homology strategy, which is a well-known security policy proposed by Netscape. Now all JavaScript-enabled browsers will use this strategy. The so-called homology is refers to, domain name, protocol, port same. When a browser's two tab pages are opened to Baidu and Google's page when a Baidu browser executes a script will check the script is which page, that is, check whether homologous, only and Baidu homologous script will be executed.

That's why you can't get the data, so how do you solve cross-domain problems? Yes, we can get to the point now to find out what JSONP is.

The simple principle of cross-domain

Just look at the definition is not very clear, then first we have to manually do a simple and easy to understand the small test. Create a new ASP.net Web program, add a sample.html Web page, and a test.js file with the following code:

Code for sample.html:

 <! DOCTYPE HTML PUBLIC "-//wc//dtd XHTML. transitional//en "" Http://www.w.org/TR/xhtml/DTD/xhtml-transitional.dtd ">
  
 

Code for Test.js:

Alert ("Success");

Open sample.html will jump out of the "success" such a message box, which does not seem to explain what, how to solve the cross-domain problem? OK, now that we're simulating a non homologous environment, we're not already creating a new Web program with Visual Studio (here we call a program), and now we're going to open a new Visual Studio and then create a new Web program (program B), Remove our previous Test.js file from program A and copy it into the B program. When both programs are running, Visual Studio starts the built-in server, assuming that a program is a localhost:20001,b program is localhost:20002, which simulates a non homologous environment (although the domain name is the same but the port number is different, so it is not homologous).

OK, we should then change the code in sample.html, because the Test.js file in the B program, the URL has become a localhost:20002.

sample.html part of the code:

<script type= "Text/javascript" src= "Http://localhost:20002/test.js" ></script>

Please keep AB two Web programs running, and when you refresh localhost:20001/sample.html again, jump out of the "Success" dialog box, yes, successfully access to the non homologous localhost:20002/ Test.js this so-called remote service. In this step, I believe you should have probably understood how cross-domain access to the principle.

The src attribute of the <script> label is not constrained by the homology policy, so you can get any server script and execute it.

The implementation mode of JSONP--callback

Just a little example of how Cross-domain works, let's go back and look at the form of JavaScript callback in Jsonp's definition notes. So let's modify the code and how to implement the Jsonp JavaScript callback form.

Part of sample code in program a:

 <script type= "Text/javascript" >
 //Callback Functions function
 callback (data) { 
   alert (data.message); 
 } 
 </script> 
 <script type= "Text/javascript" src= "Http://localhost:20002/test.js" ></script>

Code for Test.js in program B:

Call the callback function and pass the JSON data as an elaboration to complete the callback

 
 

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

Populating the JSON data into the callback function is the meaning of Jsonp's json+padding.

In general, we want this script tag to be dynamically invoked, rather than being executed as if it were not displayed on the page because it is pinned inside the HTML. We can dynamically create script tags through javascript so we can invoke remote services flexibly.

Part of sample code in program a:

 <script type= "Text/javascript" > 
   function Callback (data) { 
     alert (data.message); 
   } 
   Add <script> Tag Method 
   function Addscripttag (src) { 
   var script = document.createelement (' script '); 
     Script.setattribute ("type", "Text/javascript"); 
     SCRIPT.SRC = src; 
     Document.body.appendChild (script); 
 
   Window.onload = function () { 
     Addscripttag ("Http://localhost:/test.js"); 
   } 
 </script>

Program b test.js code unchanged, we execute the next program, is not the same as the original. If we want to invoke a remote service again, just add the Addscripttag method and the SRC value of the incoming remote service is OK. Here explains why to put the Addscripttag method into the Window.onload method, because Addscripttag method has a sentence document.body.appendChild (script); This script tag is added to the body, because the JavaScript code we write is in the head tag, Document.body has not yet initialized, so we have to initialize the page through the Window.onload method, so that we can not go wrong.

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

Q=? This question mark is the content that you want to search for, the most important is the second callback=? This is just like the name of the callback function, which is to send the function name of the callback function you defined on the client to the server, and the server will return the method of the name of the callback function you defined. Passes the obtained JSON data to this method to complete the callback. A bit wordy, or look at the implementation of the Code bar:

 <script type= "Text/javascript" > 
   //Add <script> Tag method 
   function Addscripttag (src) {
     var script = Document.createelement (' script ');
     Script.setattribute ("type", "Text/javascript");
     SCRIPT.SRC = src;
     Document.body.appendChild (script);
   Window.onload = function () {
     ///search for Apple to pass the custom callback function name result into the callback parameter
     addscripttag ("http:// Ajax.googleapis.com/ajax/services/search/web?v=.&q=apple&callback=result ");
   }
   Custom callback function
     result function Results {//We simply get the URL data alert in the first record of the Apple search results
     ( Data.responsedata.results[].unescapedurl);
   }
 </script>

There are a lot of JSONP services like this (the following information comes from using JSONP to implement Cross-domain communication, part 1th: Quickly build powerful mashups with JSONP and JQuery):

Digg API: The Headlines from Digg:

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

Geonames API: Location information for postcode:

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

Flickr JSONP API: Download the latest pictures of cats:

http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json& Jsoncallback=?

Yahoo Local Search API: Search for pizzas in zip code 10504:

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

Next, we'll create a simple remote service to achieve the same JSONP service as above. or use Web program A and program B to do the demo, this time we create a myservice.ashx file on program B.

MYSERVICE.ASHX Code for Program B:

 public class Myservice:ihttphandler 
   {public 
     void ProcessRequest (HttpContext context) 
     { 
       //Get callback function name 
       String callback = context. Request.querystring["Callback"]; 
       JSON data 
       String json = "{\" name\ ": \" Chopper\ ", \" sex\ ": \" man\ "}"; 
 
       Context. Response.ContentType = "Application/json"; 
       Output: callback function name (JSON data) context
       . Response.Write (Callback + "(" + JSON +) ");
     } 
 
     public bool IsReusable 
     { 
       get 
       {return 
         false; 
   }}}

The call in program A's sample code:

 <script type= "Text/javascript" >   function Addscripttag (src) {
     var script = document.createelement (' Script ');
     Script.setattribute ("type", "Text/javascript");
     SCRIPT.SRC = src;
     Document.body.appendChild (script);
    Window.onload = function () {
     //Call remote service     Addscripttag ("Http://localhost:/MyService.ashx?callback=person");
   }
   //callback function person function person   (data) {
     alert (Data.name + ' is a ' + Data.sex);
   }
 </script>

This completes a most basic JSONP service invocation, and is not very simple, let's look at how jquery invokes Jsonp.

The implementation of jquery on JSONP

The jquery framework also, of course, supports JSONP, and you can use the $.getjson (Url,[data],[callback]) method (refer to http://api.jquery.com/jQuery.getJSON/in detail). So we're going to modify the code for program A, and use jquery's Getjson method to do it (the following example uses no reference to the service, so it only writes 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" + Data.sex);   }) 
; </script>

The result is the same, note that the URL must be added after a callback parameter, so that the Getjson method will know that the JSONP way to access the service, callback the following question mark is an internally generated callback function name. This function name Everyone can debug a look, such as jquery17207481773362960666_1332575486681.

Of course, adding that we want to specify our own callback function name, or what do we do with a fixed callback function name on the service? We can use the $.ajax method to implement (more parameters, can refer to Http://api.jquery.com/jQuery.ajax). Let's take a look at how to achieve 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 is the person who can specify our own callback method name, and the remote service accepts the value of the callback parameter is no longer the automatically generated callback name, but the person. DataType is to specify that remote services be accessed in jsopn manner.

jquery makes it easy to implement JSONP for Cross-domain access. Let's write this for a moment. Follow-up and update, please continue to pay attention, thank you.

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.