Cross-origin access execution of Ajax Javascript

Source: Internet
Author: User
Tags subdomain subdomain name


I suddenly felt that this was the problem. After studying the problem, I thought it was quite easy, but my knowledge was still lacking. The solution was as follows:

Blocked Ajax requests

Let's verify the request blocking first. We use the followingCode:

Initiate three consecutive requestsCopy codeThe Code is as follows: function simplerequest ()
{
VaR request = new XMLHttpRequest ();
Request. Open ("Post", "script. ashx");
Request. Send (null );
}
Function threerequests ()
{
Simplerequest ();
Simplerequest ();
Simplerequest ();
}

When threerequests is executed, three requests with the same domain name will be sent consecutively, or the blocking effect will be viewed through statistical charts:

The last request is blocked by the first two requests.

It takes 1.5 seconds for each request. Obviously, the third request can only be executed after the first request is completed. Therefore, it takes more than three seconds to complete the execution. What we want to change is this situation.

Traditional cross-domain asynchronous request Solution
The only guarantee of Ajax security seems to be the restriction on Cross-Domain Ajax requests. Unless you open a webpage on the local hard disk or enable cross-domain data transmission in IE, Ajax requests to other domain names will be banned. In addition, the cross-domain judgment is very strict. Different sub-domain names, or different ports of the same domain name, will be regarded as different domain names. We cannot send Ajax requests to their resources.

On the surface, it seems that there is no way to break this restriction. Fortunately, we have a savior, that is, IFRAME!

IFRAME does not appear in the standard, but because it is actually useful, Firefox also "has to" support it (similar to innerhtml ). There are already some cross-domain name asynchronous requests on the Internet, but they are not doing well. Their simple working principle is as follows: place a specific page file in another domain name as a proxy, and the home page transmits the asynchronous request information to the proxy page in IFRAME through the query string, the proxy page places the results in the hash of its own location after the Ajax request is executed, and the homepage Round-Robin the SRC hash value of IFRAME. Once it is found that it has changed, hash is used to obtain the required information.

The implementation of this method is complex and has limited functions. In IE and Firefox, the URL length can be about 2000 characters. It may be enough for a common requirement. Unfortunately, it is far from enough to transmit a large amount of data. Compared with the solution we will propose later, its only advantage may be that it can make asynchronous requests across any domain name, and our solution can only break through the limitations of subdomain names.

Now let's take a look at our practices!

Break through the limitations of sub-domain names elegantly

The key to breaking through the subdomain name limit is IFRAME.

IFRAME is a good thing. We can access the page objects in IFRAME through subdomain names, such as the window and Dom structures, including calling Javascript (through the window object) -- we will upload the document of the internal and external pages. set domain to the same. Then, initiate different requests on the pages of different subdomains and pass the results through JavaScript. The only requirement is a simple static page as a proxy.

Now let's start writing a prototype. Although it is simple, it can explain the problem.

First, write a static page as the proxy placed in IFRAME, as follows:

Subdomainproxy.htmlCopy codeThe Code is as follows: <HTML xmlns = "http://www.w3.org/5o/xhtml">
<Head>
<Title> untitled page </title>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Document. Domain = "test.com"; function sendrequest (method, URL)
{
VaR request = new XMLHttpRequest ();
Request. Open (method, URL );
Request. Send (null );
}
</SCRIPT>
</Head>
<Body>
</Body>
</Html>

Then we will write our Home Page:

Http://www.test.com/Default.html

Copy code The Code is as follows: <HTML xmlns = "http://www.w3.org/5o/xhtml">
<Head runat = "server">
<Title> untitled page </title>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Document. Domain = "test.com"; function simplerequest ()
{
VaR request = new XMLHttpRequest ();
Request. Open ("Post", "script. ashx");
Request. Send (null );
}
Function crosssubdomainrequest ()
{
VaR proxy = Document. getelementbyid ("iframeproxy"). contentWindow;
Proxy. sendrequest ('post', 'HTTP: // sub0.test.com/script.ashx ');
}
Function threerequests ()
{
Simplerequest ();
Simplerequest ();
Crosssubdomainrequest ();
}
</SCRIPT>
</Head>
<Body>
<Input type = "button" value = "request" onclick = "threerequests ()"/>
<IFRAME src = "http://sub0.test.com/subdomainproxy.html" style =" display: none ;"
Id = "iframeproxy"> </iframe>
</Body>
</Html>

When the threerequests method is executed, resources under two different domain names, http://www.test.com and http://sub0.test.com, are requested at the same time. Obviously, the last request is no longer blocked by the first two requests:

Requests with different domain names will not be blocked

Satisfactory results!

Although it can only break through subdomain names, it is enough, isn't it? Why do we need to force asynchronous communication between any domain names? What's more, how elegant our solutions are! In the next articleArticle. In this way, the asynchronous communication layer of the client is completely transparent to developers. Is there anything more pleasant in the world? :)

Notes

It may be worth mentioning the following:

I tried this idea and found that the XMLHTTPRequest object was created, you must call both the open and send methods on the IFRAME page to successfully send Ajax requests in IE and Firefox.

In the preceding example, The Request Path to the subdomain name is http://sub0.test.com/script.ashx. Please note that the complete subdomain name cannot be omitted; otherwise, an error with insufficient permissions will occur in Firefox, when the open method is called, an exception is thrown -- it seems that Firefox treats it as a resource of the parent page domain name.
Because of the browser's security policy, the browser does not allow different domains (such as: phinest.org and lab.phinest.org), different protocols (such as: http://phinest.org and https://phinest.org), different ports (such as: http: phinest.org and http://phinest.org: 8080) the page in the lower part accesses each other through XMLHttpRequest. This problem also affects the Javascript calls and control of different pages. However, when the primary domain, protocol, and port are the same, by setting the document. domain main domain, JavaScript can access control between different sub-domain names, for example, by setting document. domain = 'phinest. org ', http: // phinest.org and http://lab.phinest.org pages can communicate with each other, which also provides solutions for XMLHttpRequest mutual access under different subdomains in this case Solution.

For Ajax cross-origin problems with the same primary domain, protocol, and port, document has been set very early. domain to solve the problem, but has never seen a specific successful application. This attempt, the principle is to use a hidden IFRAME to introduce pages across another subdomain as a proxy, use JavaScript to control the XMLHttpRequest of another subdomain introduced by IFRAME for data acquisition. Ajax access under different primary domains, protocols, and ports must be implemented through the background proxy.

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.