Several methods of cross-domain communication

1. jsonp works, reference jsonp.js

// Create ajax Reference Site [] https://segmentfault.com/a/1190000006669043
jsonp.js

jsonp = function (url, onsuccess, onerror, charset) {
     var callbackName = util.getName('tt_player');
     window[callbackName] = function () {
         if (onsuccess && util.isFunction(onsuccess)) {
             onsuccess(arguments[0]);
         }
     };
     var script = util.createScript(url + '&callback=' + callbackName, charset);
     script.onload = script.onreadystatechange = function () {
         if (!script.readyState || /loaded|complete/.test(script.readyState)) {
             script.onload = script.onreadystatechange = null;
             // 移除该script的 DOM 对象
             if (script.parentNode) {
                 script.parentNode.removeChild(script);
             }
             // 删除函数或变量
             window[callbackName] = null;
         }
     };
     script.onerror = function () {
         if (onerror && util.isFunction(onerror)) {
             onerror();
         }
     };
     document.getElementsByTagName('head')[0].appendChild(script);
 };

Loading script tags embodiment, the tip is removed ajax request code, a script tag is added, src tag points to another domain http://www.abc.com

//告诉服务端结果以jsonp的函数名返回
    <script src="http://www.abc.com/?data=name&callback=jsonp" charset="utf-8"></script>
//浏览器下发内容:
    <script type="text/javascript">
    //本地要注册一个jsonp全局函数将返回的data执行出来
       jsonp({
           data: {
      
           },
       });
    </script>

jQuery provides a way to use JSONP convenience, although similar ajax request, but the essence is not the same, and only the get request, as follows:

<!DOCTYPE html>
<html>
<head>
    <title>GoJSONP</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
</head>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type : "get",
            async: false,
            url : "http://local.sns.jutouit.com/test.php?id=1",
            dataType: "jsonp",
            jsonp:"callback", //请求php的参数名
            jsonpCallback: "jsonhandle",//要执行的回调函数(参数值)
            success : function(data) {
                alert("age:" + data.age + "  name:" + data.name + "  sex:"+data.sex);
            }
        });
    });	
</script>
</body>
</html>

2. use hash communication

A scenario is a current page embedded iframe or frame by cross-domain page B

  // 在A中伪代码如下:
  var B = document.getElementsByTagName('iframe');
  B.src = B.src + '#' + 'data';
  // 在B中的伪代码如下
  window.onhashchange = function () {
      var data = window.location.hash;
  };

3. postMessage

  // 窗口A(http:A.com)向跨域的窗口B(http:B.com)发送信息
  B:window.postMessage('data', 'http://B.com');
  // 在窗口B中监听message事件
  A:window.addEventListener('message', function (event) {
      console.log(event.origin);//http://A.com
      console.log(event.source);//Awndow
      console.log(event.data);//data
  }, false);

4.Websocket

[References] http://www.ruanyifeng.com/blog/2017/05/websocket.html

  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.');
  };

5. HEARTS

[References] http://www.ruanyifeng.com/blog/2016/04/cors.html
CORS is a W3C standard, stands for "Cross-Origin Resource Sharing" (Cross-origin resource sharing) .
It allows the browser to cross the source server, issued a request XMLHttpRequest, which overcomes the limitations of AJAX only homologous use. Communication is the key to achieving CORS server. CORS long as the server implements the interface, you can communicate across the source.
// url (mandatory), options (optional)
FETCH ( '/ some / URL /', {
Method: 'GET',
}). The then (function (Response) {

  }).catch(function (err) {
    // 出错了,等价于 then 的第二个参数,但这样更好用更直观
  });

Guess you like

Origin blog.csdn.net/qq_36711388/article/details/90346985