JSONP: Solving Ajax cross-domain problems

Source: Internet
Author: User
Tags script tag

This article mainly explains how to solve the problem of Ajax cross-domain, from the simple principle of cross-domain to the JONP implementation mode to explain the whole solution in detail, finally using jquery can be easily implemented JSONP to cross-domain access.

Last week, customers bought a new server, originally placed on the old server on the customer's web page information and a background program (ASP), in the customer's home page has a dynamic display of the latest message processing, this process is through the Ajax asynchronous from the background program obtained. Since the new server was purchased, the client wanted to separate the Web home page from the daemon, and the daemon was deployed to the new server. But this project was developed by my colleague, Comrade Fulamatu, who deployed the program separately and then made some minor changes.

"How the latest message is not taken, the asynchronous processing of the URL has also been added to the address of the new server (HTTP://XXXX.COM/.../NEWS.ASHX), strange ..." Fulamatu complained, I looked at IE7 under a script error "アクセスが reject no されました" Error (the environment is in Japanese, meaning that access is denied). Online search of the Chinese environment should be "no permission" it. There are no scripting errors on Firefox or Chrome, but this error can be measured by the Firebug tool ("Permission denied to call Method Xmlhttprequest.open").

Homologous policy

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

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

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

JSON and JSONP

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

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

Jsonp is the merchants of JSON with padding. It is an unofficial protocol that allows the server-side integration of script tags to return to the client, with the form of JavaScript callback for cross-domain access (this is just the JSONP simple implementation form). --Source Baidu

Jsonp is like a json+padding (padding here we understand to fill), let's look at the following small example and then detailed.

The simple principle of cross-domain

The definition of light is not very clear, so first of all, we first to do a manual easy to understand the small test. Create a new ASP. NET Web program, add the Sample.html Web page and a test.js file with the following code:

Sample.html's Code:

  1. <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
  2. <html xmlns="http://www.w3.org/1999/xhtml" >
  3. <head>
  4. <title>test</title>
  5. <script type="Text/javascript" src="Test.js"></script>
  6. </head>
  7. <body>
  8. </Body>
  9. </html>

Test.js's Code:

    1. Alert ("Success");

Opening sample.html will jump out of the "success" such a message box, which does not seem to explain what the cross-domain problem is how to solve it? OK, now we simulate the non-homologous environment, we have not already used Visual Studio to create a new Web program (here we call a program), now we open a new Visual Studio and create a new Web program (b program), Remove our previous Test.js file from the a program and copy it to the B program. After both programs are running, Visual studio launches the built-in server, assuming that the a program is the 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, it is non-homologous).

OK, we should next change the code in sample.html, because the Test.js file is on the B program, and the URL becomes localhost:20002.

sample.html part of the code:

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

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

The src attribute of the <script> tag is not constrained by the same-origin policy, so you can get any script on the server and execute it.

JSONP mode of implementation: CallBack

Just a small example of the principle of cross-domain, we go back and look at the JSONP definition of the description of the JavaScript callback form. So let's change the code, how to implement the Jsonp JavaScript callback form.

Part of the Code for sample in program a:

    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 for Test.js in program B:

    1. Call the callback function and use the JSON data as an elaboration pass, complete the callback
    2. Callback ({message:"Success"});

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

fill in the JSON data into the callback function, which is the meaning of Jsonp's json+padding.

In general, we want this script tag to be dynamically invoked, rather than as it is fixed in HTML, so it does not wait for the page to display. We can create script tags dynamically through JavaScript, so we can invoke remote services with flexibility.

Part of the Code for sample in program a:

  1. <script type="Text/javascript" >
  2. function Callback (data) {
  3. alert (data.message);
  4. }
  5. //How to add <script> tag
  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. Window.onload = function () {
  13. Addscripttag ("http://localhost:20002/test.js");
  14. }
  15. </script>

Program B's test.js code does not change, 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 remote service is allowed. Here is why the Addscripttag method into the Window.onload method, because the Addscripttag method has a sentence document.body.appendChild (script); This script tag is added to the body, because we write the JavaScript code in the head tag, Document.body has not been initialized, so we have to initialize the page through the Window.onload method, so that there is no error.

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

Q=? This question mark indicates what you want to search for, and most importantly, the second callback=? This is the name of the callback function, which is named after its name, that is, the function name of your client-defined callback function is passed to the server, and the server returns a method with the name of the callback function you have defined. The retrieved JSON data is passed into this method to complete the callback. A bit wordy, or look at the implementation of the Code it:

  1. <script type="Text/javascript" >
  2. //How to add <script> tag
  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. Window.onload = function () {
  10. //Search for Apple to pass the custom callback function name result into the callback parameter
  11. Addscripttag ("Http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=apple&callback=result");
  12. }
  13. //Custom callback function result
  14. function result (data) {
  15. //We'll simply get the URL data from the first record in Apple search results
  16. alert (Data.responsedata.results[0].unescapedurl);
  17. }
  18. </script>

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

Digg API: Headline News from Digg:

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

Geonames API: Location information for postal code:

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

Flickr JSONP API: Loading pictures of the latest cats:

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

Yahoo! Local Search API: Find Pisa in the 10504 area of Zip:

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

Next we create a simple remote service that implements the same JSONP service as above. or using 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:

  1. Public class Myservice:ihttphandler
  2. {
  3. public void ProcessRequest (HttpContext context)
  4. {
  5. //Get callback function name
  6. String callback = Context.  request.querystring["Callback"];
  7. //json Data
  8. String json = "{\" name\ ": \" Chopper\ ", \" sex\ ": \" man\ "}";
  9. Context.  Response.ContentType = "Application/json";
  10. //Output: callback function name (JSON data)
  11. Context.  Response.Write (Callback + "(" + JSON + ")");
  12. }
  13. Public bool IsReusable
  14. {
  15. Get
  16. {
  17. return false;
  18. }
  19. }
  20. }

Call in the sample code of program A:

  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. Window.onload = function () {
  9. //Invoke remote service
  10. Addscripttag ("Http://localhost:20002/MyService.ashx?callback=person");
  11. }
  12. //callback function person
  13. function Person (data) {
  14. Alert (Data.name + "is a" + data.sex);
  15. }
  16. </script>

This completes a most basic JSONP service call, is not very simple, below we to understand how jquery is called Jsonp.

The realization of jquery to Jsonp

The jquery framework also certainly supports JSONP, which can be used with the $.getjson (Url,[data],[callback]) method (see http://api.jquery.com/jQuery.getJSON/for details). Then we will modify the code of the program A, instead of the jquery Getjson method (The following example is useless to the service, so only write Getjson (Url,[callback])):

    1. <script type="Text/javascript" src="Http://code.jquery.com/jquery-latest.js" ></script>
    2. <script type="Text/javascript" >
    3. $.getjson ("http://localhost:20002/MyService.ashx?callback=?",function (data) {
    4. Alert (Data.name + "is a A" + data.sex);
    5. });
    6. </script>

The result is the same, note that after the URL must be added a callback parameter, so that the Getjson method will know is to use JSONP way to access the service, callback the question mark is the internal automatically generated a callback function name. This function name you can debug a bit to see, such as jquery17207481773362960666_1332575486681.

Of course, adding that we want to specify our own callback function name, or how to fix a fixed callback function name on the service? We can use the $.ajax method to implement (more parameters, detailed reference to Http://api.jquery.com/jQuery.ajax).

Let's take a look at how to achieve it:

  1. <script type="Text/javascript" src="Http://code.jquery.com/jquery-latest.js" ></script>
  2. <script type="Text/javascript" >
  3. $.ajax ({
  4. URL:"http://localhost:20002/MyService.ashx?callback=?",
  5. DataType:"Jsonp",
  6. Jsonpcallback:"Person",
  7. Success:function (data) {
  8. Alert (Data.name + "is a A" + data.sex);
  9. }
  10. });
  11. </script>

Yes, Jsonpcallback can specify our own callback method name person, and the remote service accepts that the value of the callback parameter is no longer an auto-generated callback name but a person. DataType is to specify that the remote service is accessed in jsopn manner.

jquery makes it easy to implement JSONP for cross-domain access. Let's write this for the time being.

Original link: http://www.cnblogs.com/chopper/archive/2012/03/24/2403945.html

JSONP: Solving Ajax cross-domain problems

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.