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 一样。