Analysis on solving ajax cross-origin problem by using JSONP; Analysis on jsonpajax

Source: Internet
Author: User

Analysis on solving ajax cross-origin problem by using JSONP; Analysis on jsonpajax

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 ).

JSONP is like JSON + Padding (we understand Padding as filling here). Let's take a look at the following small example and then introduce it in detail.

Same-origin policy

Why is such an error? This is because all browsers that support Javascript use the same-origin security policy. Look at Baidu's explanation:

Same-origin policy, a well-known security policy proposed by Netscape. This policy is applicable to all browsers that support JavaScript. The so-called same source means that the domain name, protocol, and port are the same. When a browser opens two tabs of Baidu and Google respectively, when a Baidu Browser executes a script, it will check which page the script belongs to, that is, whether the script is of the same origin, only scripts with the same source as Baidu are executed.

This is why data cannot be obtained. How can we solve the cross-origin problem? That's right. Now we can go to the topic to understand what JSONP is.

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:

 <!DOCTYPE html PUBLIC "-//WC//DTD XHTML . Transitional//EN" "http://www.w.org/TR/xhtml/DTD/xhtml-transitional.dtd"> 

Code for test. js:

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:

<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:

<Script type = "text/javascript"> // callback function callback (data) {alert (data. message) ;}</script> <script type = "text/javascript" src = "http: // localhost: 20002/test. js "> </script>

Code of test. js in program B:

// Call the callback function and transmit the data in json format to complete the callback.

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 form as a parameter to complete the callback.

Fill JSON data into the callback function, which 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:

<Script type = "text/javascript"> function callback (data) {alert (data. message) ;}// 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>

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:

<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 () {// search for apple, pass the custom callback function name result to the addScriptTag ("http://ajax.googleapis.com/ajax/services/search/web? V =. & q = apple & callback = result ");} // custom callback function result (data) {// obtain the url data alert (data. responseData. results []. unescapedUrl) ;}</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:

Public class MyService: IHttpHandler {public void ProcessRequest (HttpContext context) {// get the 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 ;}}}

Call in sample code of program:

<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 the remote service addScriptTag ("http: // localhost:/MyService. ashx? Callback = person ");} // callback function person (data) {alert (data. name +" is a "+ data. sex) ;}</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. There will be updates later. Please stay tuned. 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.