前后端通信

2019-04-26  本文已影响0人  不染事非
1、浏览器的同源政策限制:端口,域名,协议 ,只要一个不一样就跨域
2、前后端通信的方式
2.1 原生ajax
 function ajax(options){
            var pramas = {
                url:'',
                type: 'get',
                data: {},
                success: function (data) {},
                error: function (err) {},
            }
            options = Object.assign(pramas, options)
            if(options.url){
                var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
                var url = options.url,
                    type = options.type.toUpperCase(),
                    data = options.data,
                    dataArr = [];
                for(let key in data){
                    let value = key + '='+ data[key]
                    dataArr.push(value)
                }
                if(type === "GET"){
                    url = url + "?" + dataArr.join('&')
                    xhr.open(type, url, true)
                    xhr.send()
                }
                if(type === "POST"){
                    xhr.open(type,url, true)
                    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
                    xhr.send(dataArr.join('&'))
                }
                xhr.onreadystatechange = function(){
                    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {  // 304未修改
                        options.success(xhr.responseText)
                    }else {
                        options.error(xhr.responseText)
                    }
                }
            }
        }
2.2 Websocket

websocket 的使用说明 https://www.runoob.com/html/html5-websocket.html

2.2.1 WebSocket 是什么
2.2.2 为什么需要Websocket
// 初始化一个 WebSocket 对象
var ws = new WebSocket("ws://localhost:9998/echo");

// 建立 web socket 连接成功触发事件
ws.onopen = function () {
  // 使用 send() 方法发送数据
  ws.send("发送数据");
  alert("数据发送中...");
};

// 接收服务端数据时触发事件
ws.onmessage = function (evt) {
  var received_msg = evt.data;
  alert("数据已接收...");
};

// 断开 web socket 连接成功触发事件
ws.onclose = function () {
  alert("连接已关闭...");
};

2、跨域通信的几种方式:

// 动态创建一个script标签var script = document.createElement("script") 
   <script>
       var callback = function(res){
                console.log(res)
         }
        var script = document.createElement("script")
        script.src = " "  //请求地址 
        document.querySelector('body').appendChild(script)
    </script> 
      // postMessage
      // 窗口A(http:A.com)向跨域的窗口B(http:B.com)发送信息
      Bwindow.postMessage('data', 'http://B.com');
      // 在窗口B中监听
      Awindow.addEventListener('message', function (event) {
          console.log(event.origin);
          console.log(event.source);
          console.log(event.data);
      }, false);
  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.');
      };
fetch('/some/url/', {
          method: 'get',
      }).then(function (response) {

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

猜你喜欢

热点阅读