前端中的通信(一)

2018-06-29  本文已影响24人  阿昕_

什么是同源策略及限制

前后端如何通信

如何创建Ajax

function ajax(){
    var xhr = null;
    try{
        xhr = new XMLHttpRequest();
    } catch(e){
        xhr = new ActiveXObject('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 );
            }
            
        }
    };
};

跨域通信的几种方式

window.postMessage('data','http://a.com')
window.addEventListener('message',(event)=>{
   console.log(event.origin,event.source,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.");
};  
--------------------------------------------------
> Connection open ...
> Received Message: Hello WebSockets!
> Connection closed.

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);
});
上一篇下一篇

猜你喜欢

热点阅读