1, the preface
- Same-origin policies and restrictions
- How to create
Ajax
- Back and forth communication
- Several ways to communicate across domains
2. Same-origin policy and restriction
- Concept: The same source policy limits how sources from one source file or script can interact with resources from another, and is a security mechanism used to isolate potentially malicious files.
- Concept of source: protocol (
http/https
), domain name, port. - Restriction: not one source, do not have permission to manipulate documents of another source.
Cookie
,localStorage
,indexDB
Etc cannot be read.- Unretrievable operation
DOM
. AJAX
The request could not be sent.
3. Front-end and back-end communication
Ajax
Ajax is only suitable for same-origin communicationWebScoket
–> Is not restricted by the same origin policyCORS
–> is a new communication standard that supports homologous communication as well as cross-domain communication.
4. How to create Ajax
XMLHttpRequest
How objects work.- Compatibility processing.
- The triggering condition of the event.
- The sequence in which events are triggered.
Key code: // 1. The first step, declare XHR object, consider ie compatibility. var xhr = XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveObject('Microsoft.XMLHTTP'); // 2. Determine the request mode, such as GET/POST, etc. Get parameters are concatenated in the URL. xhr.open(method, url,trueXhr.send ()/xhr.send(data) // Check the HTTP status. Xhr.onload =function() {// determine xhr.statusif(XHR. Status = = = 200 | | XHR. Status = = = 304 | | XHR. Status = = = 206) {/ / 304, server to determine local cache / / 206, request part of the media may return resources}else{}}Copy the code
5. Several ways of cross-domain communication
- JSONP
// Principle: use asynchronous loading of script tags to implement. Just like loading script tags in the head header. Var jsonp = var jsonp =functionVar script = document.createElement() {// create a script tag'script'); // Add attributes to script, such as SRC, and specify callback functions in SRC. script.src ='http:/www.test.com/?name=zhangsan&callback=jsonp'// script loaded callback script.onload =function() {} // script load failed callback script.onerror =function() {} / / add the script to the head tag of the document. The getElementsByTagName ('head')[0].appendChild(script);
}
Copy the code
- Hash
/ / principle: Hash change page does not refresh, the change of the search will refresh the page / / in A code below var objB = document. GetElementsByTagName ('iframe') [0]; objB.src = objB.src +The '#' + 'data'; // In B, listenhashChange window.onhashchange =function() {var data = window.location.hash // Get yes# Everything after that
};
Copy the code
- postMessage
For example, source A sends data to source B. Data // The meanings of parameter A are as follows: Indicates the sent data"*"
window.postMessage('data'.'http/B.com'); Window. AddEventListerr ();'message'.function(event) { console.log(event); // event.origin // message source,'http/A.com'// event.source // A reference to window // event.data // received data},false)
Copy the code
- WebSocket
Var ws = new WebSocket('wss://.... '); // WSS /ws => encrypt/not encrypt // 2function(e) {
console.log('Start connecting... ');
ws.send('hello WebSocket! '); } // 3. Accept message ws.onMessage =function(e) {
console.log('Receive data:'+ e.data); Ws.close () // close connection} // 4. Close connection callback, confirm to close connection ws.onclose=function(e) {
console.log('Connection closed');
}
Copy the code
- CORS
// The browser will intercept the Ajax request, and if it is found to be a cross-domain request, it will add an origin in the request header. // The FETCH API of ES6 is required.'/api/uri', {// Configure the cross-domain parameter method here:'get'Params: {}}). Then (res = > {/ / success callback}). The catch (error = > {/ / failure callback})Copy the code
6, summary
- This paper mainly introduces the concept of homologous policy source and the common ways to realize cross-domain communication.