js 通信知识点总结

本文总结了JavaScript中的同源策略及其限制,详细阐述了前后端通信的方法,如AJAX、WebSocket和CORS,并探讨了创建AJAX的过程及跨域通信的多种解决方案,包括JSONP、Hash、postMessage、WebSocket和CORS等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 同源策略

浏览器限制不同源不能通信,源包括(协议:域名:端口)。非同源时

  • Cookie LocalStorage和IndexDB不能读取
  • DOM无法获取
  • AJAX不能请求

2前后端怎么通信

  • AJAX (同源)
  • WebSocket(不限制同源非同源)
  • CORS(支持同源和非同源)

3 创建ajax

  • XMLHttpRequest对象的工作流程
  • 兼容性处理
  • 事件的触发条件
  • 事件的触发顺序
function ajax1(url, type) {
    const p = new Promise((resolve, reject) => {
        const xhr = XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP');//考虑兼容性  第一步
        if (type == 'GET') {
            //拼接参数到url后面 省略
            //....
            xhr.open('GET', url, true)   //第二步
            xhr.send();                  //第三步

        } if (type == 'POST') {
            xhr.open('POST', url, true)
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
            xhr.send('参数')

        }

        xhr.onreadystatechange = function () {  //第四步
            if (xhr.readyState === 4) {
                if (xhr.status === 200||xhr.status==304) {
                    resolve(
                        JSON.parse(xhr.responseText)
                    )
                } else if (xhr.status === 404 || xhr.status === 500) {
                    reject(new Error('404 not found'))
                }
            }
        }
        xhr.send(null)
    })
    return p
}

4 跨域通信的几种方式

  • JSONP(利用script不存在跨域行,执行约定好的方法)
  • Hash(url中#号后面的东西就是hash,hash变动页面不刷新)
  • postMessage(h5中)
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  // For Chrome, the origin property is in the event.originalEvent
  // object. 
  // 这里不准确,chrome没有这个属性
  // var origin = event.origin || event.originalEvent.origin; 
  var origin = event.origin
  if (origin !== "http://example.org:8080")
    return;

  // ...
}
  • 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.");
};

CORS(支持跨域通信的ajax)

浏览器在会拦截请求,当设置cors之后 会在请求头加 origin

fetch 请求 可以设置跨域请求。没有跨域时和ajax 一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值