最具口碑的企业网站建设,企业做网站的流程,如何做好网站关键词布局,网站开发模版什么是跨域:
浏览器对于javascript的同源策略的限制,例如http://a.cn下面的js不能调用http://b.cn中的js,对象或数据(因为http://a.cn和http://b.cn是不同域),所以跨域就出现了.同域#xff1a;简单的解释就是域名相同,端口相同,协议相同
为什么需要跨域#xff1f;
在最一…什么是跨域:
浏览器对于javascript的同源策略的限制,例如http://a.cn下面的js不能调用http://b.cn中的js,对象或数据(因为http://a.cn和http://b.cn是不同域),所以跨域就出现了.同域简单的解释就是域名相同,端口相同,协议相同
为什么需要跨域
在最一开始我们知道了跨域只存在于浏览器端。而浏览器为 web 提供访问入口。我们在可以浏览器内打开很多页面。正是这样的开放形态所以我们需要对他有所限制。就比如林子大了什么鸟都有我们需要有一个统一的规范来进行约定才能保障这个安全性。
列举的方法挺多的在面试的时候只有回答1-2个就可以了可以看看前面的简单版的答案。 1.同源策略如下 特别注意两点第一如果是协议和端口造成的跨域问题“前台”是无能为力的第二在跨域问题上域仅仅是通过“URL的首部”来识别而不会去尝试判断相同的ip地址对应着两个域或两个域是否在同一个ip上。“URL的首部”指window.location.protocol window.location.host也可以理解为“Domains, protocols and ports must match”。
2. 前端解决跨域问题
一、 document.domain iframe (只有在主域相同的时候才能使用该方法)
1) 在http://www.a.com/a.html中
document.domain a.com;
var ifr document.createElement(iframe);
ifr.src http://www.script.a.com/b.html;
ifr.display none;
document.body.appendChild(ifr);
ifr.onload function(){var doc ifr.contentDocument || ifr.contentWindow.document;//在这里操作doc也就是b.htmlifr.onload null;
};
2、在http://www.script.a.com/b.html中
document.domain a.com;
二、 动态创建script
这个没什么好说的因为script标签不受同源策略的限制。
function loadScript(url, func) {var head document.head || document.getElementByTagName(head)[0];var script document.createElement(script);script.src url;script.onload script.onreadystatechange function(){if(!this.readyState || this.readyStateloaded || this.readyStatecomplete){func();script.onload script.onreadystatechange null;}};head.insertBefore(script, 0);
}
window.baidu {sug: function(data){console.log(data);}
}
loadScript(http://suggestion.baidu.com/su?wdw,function(){console.log(loaded)});
//我们请求的内容在哪里
//我们可以在chorme调试面板的source中看到script引入的内容
三、 location.hash iframe
原理是利用location.hash来进行传值。
假设域名http://a.com下的文件cs1.html要和http://cnblogs.com域名下的cs2.html传递信息。
1) cs1.html首先创建自动创建一个隐藏的iframeiframe的src指向http://cnblogs.com域名下的cs2.html页面
2) cs2.html响应请求后再将通过修改cs1.html的hash值来传递数据
3) 同时在cs1.html上加一个定时器隔一段时间来判断location.hash的值有没有变化一旦有变化则获取获取hash值
注由于两个页面不在同一个域下IE、Chrome不允许修改parent.location.hash的值所以要借助于http://a.com域名下的一个代理iframe
代码如下
先是http://a.com下的文件cs1.html文件
function startRequest(){var ifr document.createElement(iframe);ifr.style.display none;ifr.src http://www.cnblogs.com/lab/cscript/cs2.html#paramdo;document.body.appendChild(ifr);
}function checkHash() {try {var data location.hash ? location.hash.substring(1) : ;if (console.log) {console.log(Now the data is data);}} catch(e) {};
}
setInterval(checkHash, 2000);
http://cnblogs.com域名下的cs2.html:
//模拟一个简单的参数处理操作
switch(location.hash){case #paramdo:callBack();break;case #paramset://do something……break;
}function callBack(){try {parent.location.hash somedata;} catch (e) {// ie、chrome的安全机制无法修改parent.location.hash// 所以要利用一个中间的cnblogs域下的代理iframevar ifrproxy document.createElement(iframe);ifrproxy.style.display none;ifrproxy.src http://a.com/test/cscript/cs3.html#somedata; // 注意该文件在a.com域下document.body.appendChild(ifrproxy);}
}
http://a.com下的域名cs3.html
//因为parent.parent和自身属于同一个域所以可以改变其location.hash的值
parent.parent.location.hash self.location.hash.substring(1);
四: window.name iframe
window.name 的美妙之处name 值在不同的页面甚至不同域名加载后依旧存在并且可以支持非常长的 name 值2MB。
1) 创建http://a.com/cs1.html
2) 创建http://a.com/proxy.html并加入如下代码
headscriptfunction proxy(url, func){var isFirst true,ifr document.createElement(iframe),loadFunc function(){if(isFirst){ifr.contentWindow.location http://a.com/cs1.html;isFirst false;}else{func(ifr.contentWindow.name);ifr.contentWindow.close();document.body.removeChild(ifr);ifr.src ;ifr null;}};ifr.src url;ifr.style.display none;if(ifr.attachEvent) ifr.attachEvent(onload, loadFunc);else ifr.onload loadFunc;document.body.appendChild(iframe);}
/script
/head
bodyscriptproxy(http://www.baidu.com/, function(data){console.log(data);});/script
/body
3 在http://b.com/cs1.html中包含
scriptwindow.name 要传送的内容;
/script
五 postMessageHTML5中的XMLHttpRequest Level 2中的API
1) http://a.com/index.html中的代码
iframe idifr srcb.com/index.html/iframe
script typetext/javascript
window.onload function() {var ifr document.getElementById(ifr);var targetOrigin http://b.com; // 若写成http://b.com/c/proxy.html效果一样// 若写成http://c.com就不会执行postMessage了ifr.contentWindow.postMessage(I was there!, targetOrigin);
};
/script
2) http://b.com/index.html中的代码
script typetext/javascriptwindow.addEventListener(message, function(event){// 通过origin属性判断消息来源地址if (event.origin http://a.com) {alert(event.data); // 弹出I was there!alert(event.source); // 对a.com、index.html中window对象的引用// 但由于同源策略这里event.source不可以访问window对象}}, false);
/script
六CORS【这个我也不知道哈】
CORS背后的思想就是使用自定义的HTTP头部让浏览器与服务器进行沟通从而决定请求或响应是应该成功还是应该失败。
IE中对CORS的实现是xdr
var xdr new XDomainRequest();
xdr.onload function(){console.log(xdr.responseText);
}
xdr.open(get, http://www.baidu.com);
......
xdr.send(null);
其它浏览器中的实现就在xhr中
var xhr new XMLHttpRequest();
xhr.onreadystatechange function () {if(xhr.readyState 4){if(xhr.status 200 xhr.status 304 || xhr.status 304){console.log(xhr.responseText);}}
}
xhr.open(get, http://www.baidu.com);
......
xhr.send(null);
实现跨浏览器的CORS
function createCORS(method, url){var xhr new XMLHttpRequest();if(withCredentials in xhr){xhr.open(method, url, true);}else if(typeof XDomainRequest ! undefined){var xhr new XDomainRequest();xhr.open(method, url);}else{xhr null;}return xhr;
}
var request createCORS(get, http://www.baidu.com);
if(request){request.onload function(){......};request.send();
}
七JSONP
JSONP包含两部分回调函数和数据。
回调函数是当响应到来时要放在当前页面被调用的函数。
数据就是传入回调函数中的json数据也就是回调函数的参数了。
function handleResponse(response){console.log(The responsed data is: response.data);
}
var script document.createElement(script);
script.src http://www.baidu.com/json/?callbackhandleResponse;
document.body.insertBefore(script, document.body.firstChild);
/*handleResonse({data: zhe})*/
//原理如下
//当我们通过script标签请求时
//后台就会根据相应的参数(json,handleResponse)
//来生成相应的json数据(handleResponse({data: zhe}))
//最后这个返回的json数据(代码)就会被放在当前js文件中被执行
//至此跨域通信完成
jsonp虽然很简单但是有如下缺点
1安全问题(请求代码中可能存在安全隐患)
2要确定jsonp请求是否失败并不容易
八 web sockets
web sockets是一种浏览器的API它的目标是在一个单独的持久连接上提供全双工、双向通信。(同源策略对web sockets不适用)
web sockets原理在JS创建了web socket之后会有一个HTTP请求发送到浏览器以发起连接。取得服务器响应后建立的连接会使用HTTP升级从HTTP协议交换为web sockt协议。
只有在支持web socket协议的服务器上才能正常工作。
var socket new WebSockt(ws://www.baidu.com);//http-ws; https-wss
socket.send(hello WebSockt);
socket.onmessage function(event){var data event.data;
}
参考于 作者PheonixHkbxoic 链接 https://www.cnblogs.com/PheonixHkbxoic/p/5760838.html 总结
跨域问题在目前后端分离的架构中普遍存在本文所介绍的这几种方案虽然都能够解决跨域问题但其实各有优劣。比如Jsonp方式实现起来较为简单但只支持GET请求方式在原生JavaScript脚本中使用方便但是当利用了如Vue.js这种MVVM框架时就有些难以施展了。反向代理的方式无需改动后端代码但是对于整个系统而言可移植性较差CORS方式需要后端来积极配合前端实现跨域。总之没有技术银弹我们要在实际情形中比较分析选择最合适的方案。