How the front-end and back-end communicate:
Ajax
WebSocket
CORS
Several ways of cross-domain communication:
jsonp:
jsonp implements cross-domain communication by taking advantage of the fact that script tags are not restricted by the same-origin policy.
js code:
function jsonhandle(data){
alert("age:" + data.age + "name:" + data.name); } var url = "corresponded.php?id=1&callback=jsonhandle"; //Pass the callback function name to the PHP page, and then pass The PHP page returns this function (including the return data) var obj = document.createElement('script'); obj.setAttribute("src",url); document.getElementsByTagName('body')[0].appendChild(obj);<?php $callback = $_GET['callback']; $data = array( 'age' => 20, 'name' => 'Zhang San', ); echo $callback."(".json_encode($data).")"; ?>
postMessage: HTML5 is specially added for ending cross-domain;
A.js window.postMessage('this is A.js possMessage ','http://B.com'); //The first parameter is the transmitted string (if it is an object, it is also converted to a json string), the second parameter is the target URL B.js window.addEventListener('message',function(event){ //You can listen to the message event on the B page if(event.origin === 'http://A.com'){ console.log(event.data); event.source.postmessage('recive data of A.js in B.js ', event.origin); } //event.data represents the data passed in; event.origin sends the data address; event.source sends the data object; },false)
Hash: Hash is the part after # in the URL, and the page city will not be refreshed when Hash changes. Search is in the URL? The latter part, the change of Search will refresh the page
A.html: <iframe frameborder="0" id="myIframe" src="http://B.html"></iframe>
A.js: var myIframe = document.getElementById('myIframe'); myIframe.src = myIframe.src + '#' + 'data';
B.js: window.onhashchange = function() { var data = window.location.hash; }
Just monitor the hash in B.js.
WebSocket: No same-origin restriction, can communicate with any server.
var ws = new WebSocket("wss://echo.websocket.org");
ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
};
ws.onmessage = function(evt) {
console.log( "Received Message: " + evt.data);
ws.close();
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};
I recommend reading Ruan Yifeng's article:
CORS: It can be understood as Ajax that can make cross-domain requests. Using fetch to send asynchronous requests, fetch cross-domain must set the corresponding `Access-Control-Allow-Origin` in the backend to get data.
fetch('https://c.y.qq.com').then((res)=>{ console.log(res.data) }).catch((err)=>{ console.log(err) })