因为浏览器出于安全考虑,有同源策略。也就是说,如果协议
、域名
或者端口
有一个不同就是跨域,Ajax 请求会失败。
以下方法解决跨域问题:
JSONP
JSONP 的原理很简单,就是利用 <script> 标签没有跨域限制的漏洞。通过 <script> 标签指向一个需要访问的地址并提供一个回调函数来接收数据当需要通讯时。
JSONP 使用简单且兼容性不错,但是只限于 get 请求。
<script src="http://domain/api?param1=a¶m2=b&callback=jsonp"></script>
<script>
function jsonp(data) {
console.log(data)
}
</script>
jsonp(url, opts, fn)
url (String) url to fetch
opts (Object), optional
param (String) name of the query string parameter to specify the callback (defaults to callback)
timeout (Number) how long after a timeout error is emitted. 0 to disable (defaults to 60000)
prefix (String) prefix for the global callback functions that handle jsonp responses (defaults to __jp)
name (String) name of the global callback functions that handle jsonp responses (defaults to prefix + incremented counter)
fn callback
The callback is called with err, data parameters.
If it times out, the err will be an Error object whose message is Timeout.
Returns a function that, when called, will cancel the in-progress jsonp request (fn won't be called).
CORS
CORS 需要浏览器和后端同时支持。IE 8 和 9 需要通过XDomainRequest 来实现。
浏览器会自动进行 CORS 通信,实现 CORS 通信的关键是后端。只要后端实现了CORS,就实现了跨域。
服务端设置 Access-Control-Allow-Origin 就可以开启 CORS。 该属性表示哪些域名可以访问资源,如果设置通配符则表示所有网站都可以访问资源。
(后台允许前端某个站点进行访问)
接口代理
通过修改nginx服务器配置来实现
(前端修改,后台不动)
document.domain
该方式只能用于二级域名相同的情况下,比如 a.test.com 和 b.test.com 用于该方式。
只需要给页面添加 document.domain = 'test.com' 表示二级域名都相同就可以实
现跨域
postMessage
这种方式通常用于获取嵌入页面中的第三方页面数据。一个页面发送消息,另一个页面判断来源并接收消息
网友评论