Common cross-origin access methods in Javascript

Source: Internet
Author: User

Cross-origin in Javascript is restricted, but cross-origin is sometimes necessary. In this way, various experts try their best to make JavaScript obtain data across domains. Some methods are really clever.

Here we record the three commonly used cross-origin methods as follows:

 

1. Cross-origin access between different subdomains (a.example.com | B .example.com.

Cross-origin calls are common. For example, to call the.htm page under a.example.com, you need to call the getdata function on the B .htm page under B .example.com. First, refer to the B .htm page using the IFRAME framework on the.htm page.

<iframe id="b" src="http://b.example.com/b.htm" frameborder="on"></iframe>

At the same time, set document. Domain = "example.com" on the.htm page and B .htm page. In this example, a.htmobtains the window character et in B .htm and obtains the data getdatain B .htm. The document method in B .htm is as follows:

function getIframeDocument(id){    returen document.getElementById(id).contentDocument || document.getElementById(id).document;}

 

Ii. Hash transmission parameters between different domain names (www.a.com | www. B .com)

In this example, iframeautomatically adapts to the.htm region under the domain name.

How is this parameter passed? It is passed through Hash (www. B .com/ B .htm1_width | height), where the parameter width after # is the value of window. Location. Hash.

The number of records that can be transferred under the same domain

It is said that c.htmpage has been transferred to B .htmby using iframe, and B .htm controls it. Now, the relationship is: In a.htm, iframeadds B .htm, and in B .htmpage, iframeadds c.htm.

 

A.htm code:

<HTML> <IFRAME id = "B _iframe" src = "http://www. B .com/ B .htm" frameborder = "on" border = "1px" marginwidth = "0" marginheight = "0" scrolling = "no" allowtransparency =" yes "> </iframe></Body> 

The B .htm code is as follows:

<IFRAME id = "c_iframe" Height = "0" width = "0" src = "http://www.a.com/c.htm" style = "display: none "> </iframe> <SCRIPT type =" text/JavaScript "> var B _width = math.max(document.doc umentelement. clientwidth, document. body. clientwidth); var B _height = math.max(document.doc umentelement. clientheight, document. body. clientheight); console. log (B _width); var c_iframe = document. getelementbyid ("c_iframe"); console. log (c_iframe.src );C_iframe.src= C_iframe.src + "#" + B _width + "|" + B _height; // pass through hashto the width and height of B .htm./* Http://www. B .com/c.html#width | height */</SCRIPT>

The c.htm code is as follows:

<SCRIPT type = "text/JavaScript"> var B _iframe = parent.parent.doc ument. getelementbyid ("B _iframe ");// A and C are in the same domain, and you can get the dom of the B .htm framework in a.htmthrough parent.VaR hash_url = Window. Location. Hash;// The width passed in B .htm can be obtained here | heightVaR hash_width = hash_url.split ("#") [1]. Split ("|") [0] + "PX ";// Obtain values separatelyVaR hash_height = hash_url.split ("#") [1]. split ("|") [1] + "PX"; console. log ("hash_width =" + hash_width); console. log ("hash_height =" + hash_height); B _iframe.style.width = hash_width;// The A and C pages are in the same domain. You can set styles.B _iframe.style.height = hash_height; </SCRIPT>

In this way, data can be transmitted through hash. The disadvantage is that only the string type is supported and the size is limited!

 

3. Use jsonp to transfer data across domains.

What is jsonp (jsonp is JSON with padding. Due to the same-origin policy restrictions, XMLHttpRequest only allows requests to resources of the Current Source (domain name, protocol, port. For cross-origin requests, we can use the HTML Script tag to perform cross-origin requests, and return the script code to be executed in the response, where JavaScript objects can be directly transmitted using JSON. This cross-origin communication method is called jsonp .)

In general, <SCRIPT type = "text/JavaScript" src ="Call to generate the JS file address and pass callback Parameters"> </SCRIPT> to call the code to be executed.

You can also generate it using createelement ('script'), as shown below:

VaR jsonp = Document. createelement ("script"); // set its src attribute

Because JavaScript files can be called and executed wherever they are, such as various statistics such as Js. What is the callback parameter, this is to tell the page for data transmission to pass the data to me through this function.

You can try the following address:

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

The above address is the access address of the QR code, where jsoncallback =? Replace the question mark in with your custom callback function, and the other party will pass data to you through this callback function:

For example, you can name a callback function vvgcallback:

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

Then the JS generated by the other party is like this (you can copy the above address to the address bar for testing ):

vvgcallback({        "title": "Recent Uploads tagged cat",        "link": "http://www.flickr.com/photos/tags/cat/",        "description": "",        "modified": "2012-08-15T06:07:40Z",        "generator": "http://www.flickr.com/",        "items": [       {            "title": "A squirell about to jump",            "link": "http://www.flickr.com/photos/64477042@N00/7786494040/",            "media": {"m":"http://farm9.staticflickr.com/8422/7786494040_a7a506dfdc_m.jpg"},            "date_taken": "2012-08-10T15:19:40-08:00",            "description": " <p><a href=\"http://www.flickr.com/people/64477042@N00/\">Dr arun kapoor<\/a> posted a photo:<\/p> <p><a href=\"http://www.flickr.com/photos/64477042@N00/7786494040/\" title=\"A squirell about to jump\"><\/a><\/p> <p><\/p>",            "published": "2012-08-15T06:07:40Z",            "author": "nobody@flickr.com (Dr arun kapoor)",            "author_id": "64477042@N00",            "tags": "barcelona china california birthday christmas city family flowers blue autumn friends england blackandwhite bw food dog baby india house holiday chicago canada black france flower color berlin green bird art fall film beach halloween church girl car fashion birds animals bike festival architecture clouds cat canon germany garden de geotagged fun graffiti hawaii dance football concert asia europe day florida band australia iphone instagramapp"       },       {            "title": "catkeywest",            "link": "http://www.flickr.com/photos/marshawheatley/7786461540/",            "media": {"m":"http://farm8.staticflickr.com/7120/7786461540_5e3e28bd3a_m.jpg"},            "date_taken": "2012-08-14T22:57:21-08:00",            "description": " <p><a href=\"http://www.flickr.com/people/marshawheatley/\">MarshaWheatley<\/a> posted a photo:<\/p> <p><a href=\"http://www.flickr.com/photos/marshawheatley/7786461540/\" title=\"catkeywest\"><\/a><\/p> ",            "published": "2012-08-15T06:08:53Z",            "author": "nobody@flickr.com (MarshaWheatley)",            "author_id": "85010317@N04",            "tags": "old cat town florida keywest"       }]})

It is equivalent to executing the vvgcallback () function on the page. The center of the brackets is the transmitted JSON data. In this way, you want to execute the above Code on your page. In this way, data is transmitted across domains.

 

Original article: http://www.cnblogs.com/NNUF/archive/2012/08/15/2639793.html

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.