JavaScript cross-domain access is a common problem for web developers, what is a cross-domain, a script loaded on one domain Gets or operates document properties on another domain , and the following lists three ways to implement the JavaScript cross-domain approach:
1. Cross-domain implementation based on IFRAME
Cross-domain requirements based on IFRAME implementations two domains have aa.xx.com,bb.xx.com, which means that two pages must belong to one base domain (for example, xxx.com, or xxx.com.cn), using the same protocol (for example, HTTP) and the same port (for example, are all 80), so that in two pages simultaneously add document.domain, you can implement the parent page call the function of the child page, the code is as follows:
Page One:
HTML code
- <html>
- <head>
- <script>
- document.domain = "xx.com";
- function aa () {
- Alert ("P");
- }
- </Script>
- </head>
- <body>
- <iframe src= "http://localhost:8080/CmsUI/2.html" id="i">
- </iframe>
- <script>
- document.getElementById (' i '). onload = function () {
- var d = document.getElementById (' i '). Contentwindow;
- D.A ();
- };
- </Script>
- </Body>
- </html>
Page Two:
HTML code
- <html>
- <head>
- <script>
- document.domain = "xx.com";
- function A () {
- Alert ("C");
- }
- </Script>
- </head>
- <body>
- </Body>
- </html>
At this time, the parent page can invoke the a function of the child page, realize the JS cross-domain access
2. Cross-domain based on script tags
The script tag itself can access resources from other domains and is not subject to the browser's same-origin policy, and can be created by dynamically creating a script tag on the page as follows:
Java code
- var script = document.createelement (' script ');
- SCRIPT.SRC = "Http://aa.xx.com/js/*.js";
- Document.body.appendChild (script);
In this way, by dynamically creating the script tag can load the other domain JS file, and then through this page can invoke the function of the loaded JS file, the flaw is that can not load other domain documents, can only be JS file, JSONP is implemented in this manner, JSONP returns the callback parameter value and the JSON string as a JavaScript function by passing in a callback parameter to the other domain through the background of the other domain, because the request is made through the script tag. The browser will parse the returned string according to JavaScript, implementing the data transfer between domain and domain.
The support for JSONP in jquery is also based on this scenario.
Using Jsonp for cross-domain access reference addresses Good article: http://kb.cnblogs.com/page/139725/
In addition, there are
3. Using IFRAME and Location.hash
4, Window.name realization of cross-domain data transfer
5. Use HTML5 postMessage
6. Using Flash
Implementing Cross-Domain access