What is cross-domain?
Concept: As long as there is any difference in the protocol, domain name, or port, it is regarded as a different domain.
The code copy 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
http://www.a.com/script/b.js Different folders under the same domain name are allowed
http://www.a.com:8000/a.js
http://www.a.com/b.js The same domain name, different ports are not allowed
http://www.a.com/a.js
https://www.a.com/b.js The same domain name, different protocols do not allow
http://www.a.com/a.js
http://70.32.92.74/b.js Domain name and domain name correspond to IP are not allowed
http://www.a.com/a.js
http://script.a.com/b.js The main domain is the same, but the subdomain is not allowed
http://www.a.com/a.js
http://a.com/b.js The same domain name, different secondary domain names (same as above) are not allowed (there is no access to cookies in this case)
http://www.cnblogs.com/a.js
http://www.a.com/b.js Different domain names are not allowed
The difference between ports and protocols can only be solved through the background.
Cross-domain resource sharing (CORS)
CROS (Cross-Origin Resource Sharing) cross-domain resource sharing defines how the browser and the server should communicate when accessing cross-domain resources. The basic idea behind CROS is to use a custom HTTP header to let the browser communicate with the server, thereby deciding whether the request or response should be successful or failed.
The code copy is as follows:
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "/trigkit4",true);
xhr.send();
</script>
The above trigkit4 is a relative path. If we want to use CORS, the relevant Ajax code may look like this:
The code copy is as follows:
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://segmentfault.com/u/trigkit4/",true);
xhr.send();
</script>
The difference between the code and the previous one is that the relative path is replaced with the absolute path of other domains, that is, the interface address you want to access across domains.
The server-side support for CORS is mainly achieved by setting Access-Control-Allow-Origin. If the browser detects the corresponding settings, Ajax can be allowed to access across domains.
To solve cross-domain problems, we can use the following methods:
Cross-domain via jsonp
Now the question is? What is jsonp? Wikipedia's definition is: JSONP (JSON with Padding) is a "use mode" of the data format JSON, which allows web pages to request information from other domains.
JSONP is also called fill-in JSON. It is a new method to apply JSON, but it is just a JSON included in function calls, for example:
The code copy is as follows:
callback({"name","trigkit4"});
JSONP consists of two parts: callback function and data. A callback function is a 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, it is not possible to directly request data on different domains using XMLHttpRequest. However, it is OK to introduce js script files on different domains on the page, and jsonp uses this feature to achieve it. For example:
The code copy 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 we specified in the url parameter will be executed, and the json data we need will be passed in as parameters. Therefore, jsonp requires the server-side page to cooperate accordingly.
The code copy is as follows:
<?php
$callback = $_GET['callback'];//Get the callback function name
$data = array('a','b','c');//The data to be returned
echo $callback.'('.json_encode($data).')';//Output
?>
Finally, the output is: dosomething(['a','b','c']);
If your page uses jquery, then the encapsulation method can be used to perform jsonp operations very conveniently.
The code copy is as follows:
<script type="text/javascript">
$.getJSON('http://example.com/data.php?callback=?,function(jsondata)'){
// Process the obtained json data
});
</script>
jquery will automatically generate a global function to replace the question mark in callback=?, and then it will automatically destroy the data after obtaining it. In fact, it plays the role of a temporary agent function. The $.getJSON method will automatically determine whether it is cross-domain. If it is not cross-domain, it will call the ordinary ajax method; if it is cross-domain, it will call the jsonp callback function in the form of asynchronous loading of js files.
Pros and cons of JSONP
The advantages of JSONP are: it is not restricted by homologous policies like the Ajax request implemented by the XMLHttpRequest object; it has better compatibility and can run in older browsers, without the support of XMLHttpRequest or ActiveX; and after the request is completed, the result can be returned by calling callback.
The disadvantage of JSONP is that it only supports GET requests and not other types of HTTP requests such as POST; it only supports cross-domain HTTP requests, and cannot solve the problem of how to make JavaScript calls between two pages in different domains.
Comparison between CROS and JSONP
Compared with JSONP, CORS is undoubtedly more advanced, convenient and reliable.
1. JSONP can only implement GET requests, while CORS supports all types of HTTP requests.
2. Using CORS, developers can use ordinary XMLHttpRequest to initiate requests and obtain data, which has better error handling than JSONP.
3. JSONP is mainly supported by old browsers. They often do not support CORS, and most modern browsers already support CORS).
Cross-subdomain by modifying document.domain
Browsers have a homologous policy, and one of its limitations is that in the first method we said that documents from different sources cannot be requested through the ajax method. Its second limitation is that the JS interaction cannot be performed between frameworks of different domains in the browser.
Different frameworks can obtain window objects, but they cannot obtain corresponding properties and methods. For example, there is a page with the address of http://www.example.com/a.html . There is an iframe in this page, and its src is http://example.com/b.html. Obviously, this page has a different domain from the iframe framework inside it, so we cannot get things in the iframe by writing js code in the page:
The code copy is as follows:
<script type="text/javascript">
function test(){
var iframe = document.getElementById('ifame');
var win = document.contentWindow;//You can get the window object in the iframe, but the properties and methods of the window object are almost unavailable
var doc = win.document;//The document object in the 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 come in handy. We just need to set document.domain of both pages: http://www.example.com/a.html and http://example.com/b.html to the same domain name. But it should be noted that the setting of document.domain is limited. We can only set document.domain to its own or higher parent domain, and the main domain must be the same.
1. Set document.domain in the page http://www.example.com/a.html:
The code copy is as follows:
<iframe id = "iframe" src="http://example.com/b.html" onload = "test()"></iframe>
<script type="text/javascript">
document.domain = 'example.com';//Set as main domain
function test(){
alert(document.getElementById('iframe').contentWindow);//contentWindow can obtain the window object of the child window
}
</script>
2. Also set document.domain in the page http://example.com/b.html:
The code copy is as follows:
<script type="text/javascript">
document.domain = 'example.com';//Load this page in iframe and set document.domain to make it the same as document.domain on the main page
</script>
The method of modifying document.domain is only suitable for interactions between frameworks with different subdomains.