Ajax cross-origin has always been a troublesome issue. For example, in a project, the broken bridge and the damaged snow used open to open a new page with a different domain name from the parent window, the result subwindow cannot be passed to the parent window. For example, I cannot get the page content under the love.2fool.cn domain name under www.2fool.cn. Cross-domain restrictions of browsers are designed to ensure security. However, when we want to request the content of another domain name under one domain name, we feel less comfortable.
I have used the JSONP method in WordPress weather plug-in and ingress API processing to implement cross-origin. Today, I want to solve the problem of cross-subdomain Ajax by using document. domain and iframe of JS.
Principle
Set the same document for the home page and request page. domain, spoofing the browser to achieve cross-domain Ajax effect. This method is tested in IE, chrome, Firefox, Safari, and Opera.
Disadvantage: communication between different primary domain names cannot be realized. When another iframe is included in a page, a security exception occurs and access is denied.
Use document. domain + iframe for cross-origin instances
First, let's assume that the home page address is. We need to set document on the home page. domain is 2fool.cn, and then an iframe is added to the Home Page. src is a url under the domain name work.2fool.cn, and the document is also set on the iframe page. domain is 2fool.cn, and Ajax functions need to be added to iframe, for example, jQuery. js.
The main code of the Main Page index.html is as follows:
Copy to ClipboardReference content: [www.bkjia.com] <button onclick = "crossDomain ();"> start cross-origin </button>
<Div id = "ajax"> </div>
<Iframe src = "http://work.2fool.cn/crossdomain/iframe.html" id = "iframe" style = "display: none;">
</Iframe>
<Script type = "text/javascript">
Document. domain = '2fool. cn ';
Function crossDomain (){
Var iframe = document. getElementById ('iframe'). contentWindow. $;
Iframe. get ("http://work.2fool.cn/crossdomain/helloworld.txt", function (data ){
Document. getElementById ("ajax"). innerHTML = data;
});
}
</Script>
The main code of the iframe page is as follows:
Copy to ClipboardReference: [www.bkjia.com] <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"> </script>
<Script type = "text/javascript">
Document. domain = '2fool. cn ';
</Script>
Demo: Click to view and download the Demo.