Comparison of advantages and disadvantages of js cross-origin Problems and Solutions

Source: Internet
Author: User

Comparison of advantages and disadvantages of js cross-origin Problems and Solutions

What is cross-origin?

Concept: as long as the Protocol, domain name, and port are different, they are regarded as different domains.

Copy codeThe Code is as follows:
URL indicates whether communication is allowed
Http://www.a.com/a.js
Http://www.a.com/ B .js allowed under the same domain name
Http://www.a.com/lab/a.js
Different folders under the same domain name allow http://www.a.com/script/ B .js
Http://www.a.com: 8000/a. js
Http://www.a.com/ B .js with the same domain name, different ports not allowed
Http://www.a.com/a.js
Https://www.a.com/ B .js for the same domain name, different protocols are not allowed
Http://www.a.com/a.js
Http: // 70.32.92.74/B. js domain name and the corresponding ip address of the domain name are not allowed
Http://www.a.com/a.js
The primary domain of the http://script.a.com/ B .js is the same and different subdomains are not allowed
Http://www.a.com/a.js
The same domain name of the http://a.com/ B .js, different second-level domain names (same as above) are not allowed (cookie in this case is not allowed to access)
Http://www.cnblogs.com/a.js
Different http://www.a.com/ B .js domain names are not allowed

Different ports and protocols can only be solved through the background.

Cross-origin Resource Sharing (CORS)

CROS (Cross-Origin Resource Sharing) Cross-Origin Resource Sharing defines how the browser communicates with the server when accessing Cross-Origin resources. The basic idea behind CROS is to use a custom HTTP header to allow the browser to communicate with the server and decide whether the request or response should succeed or fail.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var xhr = new XMLHttpRequest ();
Xhr. open ("getting GET", "/trigkit4", true );
Xhr. send ();
</Script>

The above trigkit4 is a relative path. If CORS is to be used, the relevant Ajax code may be as follows:

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var xhr = new XMLHttpRequest ();
Xhr. open ("getting GET", "http://segmentfault.com/u/trigkit4/", true );
Xhr. send ();
</Script>

The difference between the Code and the previous Code is that the relative path is replaced with the absolute path of other domains, that is, the interface address for cross-origin access.

The server supports CORS mainly by setting Access-Control-Allow-Origin. If the browser detects the corresponding settings, Ajax can be allowed for cross-origin access.

To solve cross-origin problems, we can use the following methods:

Cross-origin through jsonp

What's the problem? What is jsonp? The definition of Wikipedia is: JSONP (JSON with Padding) is a "usage mode" of the data format JSON, which allows the webpage to ask for information from other domains.

JSONP is also called the filling JSON. It is a new method to apply JSON, but it is included in the JSON of function calls. For example:

Copy codeThe Code is as follows:
Callback ({"name", "trigkit4 "});

JSONP consists of the callback function and data. The callback function is the function that should be called on the page when the response arrives, and the data is the JSON data passed into the callback function.

In js, we cannot directly use XMLHttpRequest to request data in different domains. However, it is possible to introduce js script files in different domains on the page, and jsonp is implemented by using this feature. For example:

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function dosomething (jsondata ){
// Process the obtained json data
}
</Script>
<Script src = "http://example.com/data.php? Callback = dosomething "> </script>

After the js file is loaded successfully, the function specified in the url parameter will be executed, and the json data we need will be passed in as the parameter. Therefore, jsonp requires the server-side pages to be matched accordingly.

Copy codeThe Code is as follows:
<? Php
$ Callback = $ _ GET ['callback']; // GET the callback function name.
$ Data = array ('A', 'B', 'C'); // data to be returned
Echo $ callback. '('. json_encode ($ data). ')'; // output
?>

Finally, the output result is: dosomething (['A', 'B', 'C']);

If jquery is used on your page, jsonp operations can be easily performed through its encapsulation method.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
$. GetJSON ('HTTP: // example.com/data.php? Callback = ?, Function (jsondata )'){
// Process the obtained json data
});
</Script>

Jquery automatically generates a global function to replace callback =? After obtaining the data, it will be automatically destroyed, which is actually a temporary proxy function. $. The getJSON method automatically determines whether the cross-origin function is used. If the cross-origin method is not used, the common ajax method is called. If the cross-origin method is used, the jsonp callback function is called in the form of Asynchronously loading js files.

Advantages and disadvantages of JSONP

JSONP has the following advantages: it is not subject to same-origin policy restrictions as Ajax requests implemented by XMLHttpRequest objects; it has better compatibility and can be run in older browsers, XMLHttpRequest or ActiveX is not required. After the request is completed, you can call callback to return the result.

The disadvantage of JSONP is that it only supports GET requests but not POST and other types of HTTP requests. It only supports cross-origin HTTP requests, it cannot solve the problem of how to call JavaScript between two pages in different domains.

Comparison between CROS and JSONP

CORS is more advanced, convenient, and reliable than JSONP.

1. JSONP can only implement GET requests, while CORS supports all types of HTTP requests.

2. With CORS, developers can use common XMLHttpRequest to initiate requests and obtain data, which provides better error handling than JSONP.

3. JSONP is mainly supported by old browsers, which often do not support CORS, but most modern browsers already support CORS ).
Cross-subdomain by modifying document. domain

Browsers all have a same-source policy. One of its limitations is that the first method we mentioned cannot request documents in different-source databases through ajax. Its second restriction is that JavaScript interaction cannot be performed between frames of different domains in the browser.
Different frameworks can obtain window objects, but cannot obtain corresponding properties and methods. For example, there is a page where its address is http://www.example.com/a.html, there is an iframe in this page, its src is a http://example.com/ B .html, obviously, this page is different from the iframe framework in it, so we cannot get the content in iframe by writing js code in the page:

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function test (){
Var iframe = document. getElementById ('invalid ifame ');
Var win = document. contentWindow; // you can obtain the window object in iframe, but the properties and methods of the window object are almost unavailable.
Var doc = win.doc ument; // The document Object in iframe cannot be obtained here
Var name = win. name; // The name attribute of the window object cannot be obtained here.
}
</Script>
<Iframe id = "iframe" src = "http://example.com/ B .html" onload = "test ()"> </iframe>

At this time, document. domain can be used, we just need to http://www.example.com/a.html and http://example.com/ B .htmlthe two pages of document.domainare set to the same domain name. However, there are limits on document. domain settings. We can only set document. domain to its parent domain or a higher level, and the primary domain must be the same.

1. Set document. domain in page http://www.example.com/a.html:

Copy codeThe Code is as follows:
<Iframe id = "iframe" src = "http://example.com/ B .html" onload = "test ()"> </iframe>
<Script type = "text/javascript">
Document. domain = 'example. com'; // set it to the primary domain.
Function test (){
Alert (document. getElementById ('delimiterame'). contentWindow); // contentWindow obtains the window object of the subwindow.
}
</Script>

2. Also set document. domain in the page http://example.com/ B .html:

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Document. domain = 'example. com'; // you can set document. domain on the iframe loading page to make it the same as document. domain on the homepage.
</Script>

The document. domain modification method is only applicable to the interaction between frames of different subdomains.

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.