前后端通信

  • 什么是同源策略及限制
  • 前后端如何通信
  • 创建ajax
  • 跨域通信的几种方式

同源策略及限制

同源策略限制从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键的安全机制

所谓同源是指,域名,协议,端口相同。

cookie,localstorage,dom 没办法相互获取 ,ajax请求也不能


前后端如何通信

ajax、websocket 、cors


创建ajax

function ajaxFunction(options){
    var xhr = XMLHttpRequest?new XMLHttpRequest : new  ActiveXObject('Microsoft.XMLHTTP');
    var url = options.url;
    if(options.type=='GET'){
        url = url + options.datas.join('&');
        xhr.open(options.type,url,true)
        xhr.send();
    }else{
        xhr.open(options.type,url,true)
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
        xhr.send(options.datas.join('&'));
    }

    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200 || xhr.status == 304 || xhr.status ==206){
                options.success.call(xhr,xhr.responseText)
            }
        }
    }

}

onreadystatechange  每次状态改变所触发事件的事件处理程序。

    responseText     从服务器进程返回数据的字符串形式。

    responseXML    从服务器进程返回的DOM兼容的文档数据对象。

    status           从服务器返回的数字代码,比如常见的404(未找到)和200(已就绪)

    status Text       伴随状态码的字符串信息

    readyState       对象状态值

    0 (未初始化) 对象已建立,但是尚未初始化(尚未调用open方法)

    1 (初始化) 对象已建立,尚未调用send方法

    2 (发送数据) send方法已调用,但是当前的状态及http头未知

    3 (数据传送中) 已接收部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误,

    4 (完成) 数据接收完毕,此时可以通过通过responseXml和responseText获取完整的回应数据


跨域通信的方法

第一种:jsonp

function jsonpCallback(result){
    console.log(result);
}

var JSONP = document.createElement('script');
JSONP.type='text/javascript';
JSONP.src='http://crossdomain.com/service.php?callback=jsonpCallback';
document.getElementByTagName('head')[0].appendChild(JSONP);

第二种:iframe+hash

// 利用hash,场景是当前页面 A 通过iframe或frame嵌入了跨域的页面 B
// 在A中伪代码如下:
var bPage = document.getElementsByTagName('iframe');
bPage.src = bPage.src+"#"+'youData';
// 在B中的伪代码如下
window.onhashchange = function(){
    var data = window.location.hash;
}

第三种:使用HTML5 postMessage

otherWindow.postMessage(message, targetOrigin);otherWindow: 对接收信息页面的window的引用。可以是页面中iframe的contentWindow属性;window.open的返回值;通过name或下标从window.frames取到的值。
message: 所要发送的数据,string类型。
targetOrigin: 用于限制otherWindow,“*”表示不作限制

 a.com/index.html中的代码

<iframe id="ifr" src="b.com/index.html"></iframe>
<script type="text/javascript">
window.onload = function() {
    var ifr = document.getElementById('ifr');
    var targetOrigin = 'http://b.com';  // 若写成'http://b.com/c/proxy.html'效果一样
    ifr.contentWindow.postMessage('I was there!', targetOrigin);
};

b.com/index.html中的代码:

 window.addEventListener('message', function(event){
        // 通过origin属性判断消息来源地址
        if (event.origin == 'http://a.com') {
            alert(event.data);    // 弹出"I was there!"
            alert(event.source);  // 对a.com、index.html中window对象的引用
                                  // 但由于同源策略,这里event.source不可以访问window对象
        }
    }, false);

 第四种:websocket

var ws = new WebSocket('wws://.....');
ws.open = function(event){
    ws.send('hello');
}

ws.onmessage = function(event){
    console.log(event.data);
}

第五种:CORS

// CORS【参考资料】http://www.ruanyifeng.com/blog/2016/04/cors.html
      // url(必选),options(可选)
      fetch('/some/url/', {
          method: 'get',
      }).then(function (response) {

      }).catch(function (err) {
        // 出错了,等价于 then 的第二个参数,但这样更好用更直观
      });
原文地址:https://www.cnblogs.com/myzy/p/7495823.html