前端中的通信(一)

什么是同源策略及限制

  • 源:协议(http/https/ws)+域名(www.baidu.com)+端口(80),不一样就是跨域了。
  • 同源策略:限制两个不同的源之间的资源交互,是用于隔离潜在恶意文件的安全机制。
  • 限制:
    – cookie、localStorage、indexDB无法读取
    – DOM无法获得
    – Ajax请求不能发送

前后端如何通信

  • Ajax
  • websocket
  • CORS

如何创建Ajax

  • 创建ajax对象(兼容处理)
  • open()
  • send()
  • onreadystatechange
  • readyState
  • status
  • JSON.parse(xhr.responseText)
function ajax(){
    var xhr = null;
    try{
        xhr = new XMLHttpRequest();
    } catch(e){
        xhr = new aActiveXObject('Microsoft.XMLHTTP');
    }

    xhr.open('get','getNews.php',true);
    xhr.send();

    /*
    xhr.open('post','1.post.php',true);
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');//申明发送的数据类型
    xhr.send('username=刘&age=3');
    */

    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if( xhr.status ==200 || xhr.status ==304  ){
                //alert( xhr.responseText );//string
                var data = JSON.parse(xhr.responseText);
            }else{
                alert( '出错了,Err:' + xhr.status );
            }

        }
    };
};

跨域通信的几种方式

  • jsonp :动态添加<script>标签,执行服务器返回的函数
  • hash :hash改变页面不会刷新,改变hash后,监听hash变化,获取数据
  • postMessage :
window.postMessage('data','http://a.com')
window.addEventListener('message',(event)=>{
   console.log(event.origin,event.source,event.data) 
},false)
  • websocket :
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.");
};  
--------------------------------------------------
> Connection open ...
> Received Message: Hello WebSockets!
> Connection closed.
  • CORS(Cross-Origin Resource Sharing, 跨源资源共享) : 浏览器会拦截ajax请求,如果是跨域的,会在http请求中添加origin
fetch("/a/url",{
    method:'get',
}).then(
    function(response){
        if(response.status!==200){
            console.log("存在一个问题,状态码为:"+response.status);
            return;
        }
        //检查响应文本
        response.json().then(function(data){
            console.log(data);
        });
    }
).catch(function(err){
    console.log("Fetch错误:"+err);
});

个人链接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值