Javascript cross-origin Access Solution

Source: Internet
Author: User
Tags in domain to domain

Due to security considerations, JavaScript is restricted by cross-origin access capabilities. But sometimes we want to do some reasonable cross-origin access things, what should we do?

There are two types of situations:

1. Access pages between subdomains based on the same parent domain
See the following three domain domains:

1. taobao.com
2. jipiao.taobao.com
3. promotion.taobao.com

They have the same parent domain taobao.com

2. Access between pages of different parent domains
See the following three domain domains:

1. taobao.com
2. Baidu.com

3. sina.com.cn

They have different parent domains.

Cross-origin solutions:

<! -- [If! Supportlists] --> ① <! -- [Endif] -->ServerProxy:The page Js of Domain A needs to access the Link under Domain B to obtain data. This scheme creates a proxy Program (possibly any server program such as ASP and Servlet) on the server side of Domain ), the page Js of Domain A directly calls the proxy program in this domain. The proxy program is responsible for sending the request to the link under Domain B and obtaining the data, finally, return the data to the page JS using the proxy.

The access process is: JS under Domain A -- links under Proxy under Domain A --- links under Domain B under Domain

Example:

Step 1:

Domain A: Javascript script on the http://Jipiao.taobao.com/test.htm page

View plaincopy to clipboardprint?
  1. <MCE: Script Type = "text/JavaScript"> <! --
  2. VaR Surl = "http://Jipiao.taobao.com/proxy.do"; // The proxy address in this domain
  3. VaR callback =
  4. {
  5. Success: function (RES) {alert (res. responsetext );},
  6. Failure: function (RES) {alert ('failure ');},
  7. Argument :{}
  8. }
  9. Yahoo. util. Connect. asyncrequest ('get', Surl, callback, null );
  10. // --> </MCE: SCRIPT>

Step 2:

Proxy Program (this is assumed to be a servlet ):

View plaincopy to clipboardprint?
  1. Public class proxy extends ....... {
  2. ... Doget (........) {
  3. Httpclient client = ......;
  4. Getmethod get = new getmethod ("www.baidu.com/xxxxx.do"); // access the link of Domain B
  5. Int statuscode = client.exe cutemethod (get );
  6. If (statuscode! = Httpstatus. SC _ OK ){
  7. Byte [] responsebody = Get. getresponsebody ();
  8. String res = new string (responsebody );
  9. Httpresponse. getwriter (). Write (RES );//
  10. Return data to the domain
  11. A
  12. }
  13. }
  14. }

<! -- [If! Supportlists] --> ② <! -- [Endif] -->Script tag: Write an empty script tag in the head of the http://Jipiao.taobao.com/test.htm for domain a page

View plaincopy to clipboardprint?
  1. <HTML>
  2. <Head>
  3. <MCE: script id = "remotescript" type = "text/JavaScript" src = "mce_src ="/> <! --
  4. <Head>
  5. <Body>
  6. <SCRIPT type = "text/JavaScript">
  7. VaR remotescript = Document. getelementbyid ('remotescript ');
  8. Remotescript. src = "www.baidu.com/xxxxx.dow.#// link to Domain B
  9. Alert (remote. Test); // use JSON data returned by Domain B
  10. Alert (F [0]);
  11. // --> </MCE: SCRIPT>
  12. </Body>
  13. </Html>

Note: This scheme requires that the data returned by Domain B be in legal JSON format or JS file format.

The format of data returned by Domain B is as follows:

View plaincopy to clipboardprint?
  1. VaR remote = {test: 'hello '};
  2. VaR F = ['2, 1];
  3. {"Test": "hello", "arrays": [2, 1]}

 

There is a third method for accessing pages between subdomains based on the same parent domain:
HideIFRAME:That is, write a hidden IFRAME on the page of the Domain A jipiao.taobao.com/yyyy.htm,

View plaincopy to clipboardprint?
  1. <HTML>
  2. <Head>
  3. <Head>
  4. <Body>
  5. <MCE: Script Type = "text/JavaScript"> <! --
  6. Document. Domain = "taobao.com ";
  7. VaR remotehtml = Document. getelementbyid ("remotehtml ");
  8. Remotehtml. src = "promotion.taobao.com/xxxx.htm?#// access the link of Domain B
  9. VaR document = remotehtml. contentdocument;
  10. ... // Here we can use document to operate the xxx.htm data on the page in Domain B.
  11. // --> </MCE: SCRIPT>
  12. <IFRAME id = "remotehtml" src = "mce_src =" style = "" diapay: none "/" mce_style = "" diapay: none "/">
  13. </Body>
  14. </Html>

Here, the promotion.taobao.com/xxxx.htm page also needs to set document. Domain = "taobao.com", this method can work. This IFRAME method is not suitable for cross-domain communication between different parent domains because it sets document. domain can only be set to its own parent domain, rather than other domains. For example, jiapiao.taobao.com can only be set to document. domain = "taobao.com" instead of document. domain = "Baidu.com"

Comparison of advantages and disadvantages:

The three solutions listed here have their respective advantages and disadvantages:

The advantage of the proxy solution is that it can be used for almost all cross-origin access, and only needs to be developed in one domain, and the other domain can provide data of any type. The disadvantage is that this scheme passes through the intermediate proxy, so the latency may be slightly higher, and the load on the local server will be increased, and the Development workload will be slightly larger.

The script tag solution is very simple and can be done without a few lines of code. However, it has strict requirements on the format of returned data and can only be JSON data, for data in other formats, this method is useless.

Hiding IFRAME is also very simple. It can process any returned data format, but it is only applicable to cross-origin requests with the same parent domain, and requires that other domains be developed in combination, you need to set document. domain

Read articles: http://www.cnblogs.com/passer/archive/2008/07/16/1243811.html

======================

Supplement: the script TAG method requires that the JSON returned by the server must have a handle, for example, JSON =. This is because the client must use this handle for reference. If no, the client JS is executed only in the VaR JSON = eval (jsonstr) mode, and the efficiency is not very high. Another way is to pass in the callback method from the client. For example, xxxx. do? Callbackapi = Ca

After receiving the callbackapi parameters, the server packs JSON in CA, for example, Ca ({.....});

The callback function defined by the client can be accessed.

Function Ca (JSON ){

.......

}

In any case, this method is coupled with the server.

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.