由于浏览器出于安全考虑,有同源策略。也就是说,若是协议、域名或者端口有一个不一样就是跨域,Ajax请求会失败。html
JSONP(JSON with Padding)的原理很简单,就是利用 <script>标签没有跨域限制的漏洞。当须要通信时,经过 <script>标签指向一个须要访问的地址并提供一个回调函数来接收数据。json
<script src="http://domain/api?param1=a¶m2=b&callback=jsonp"></script> <script> function jsonp(data) { console.log(data) } </script>
JSONP 使用简单且兼容性不错,可是只限于 get 请求.后端
接下来举一个使用jsonp实现淘宝联想词(动态生成和销毁script)的例子:api
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>联想词</title> <style> body,ul,li{ margin: 0; padding: 0; list-style: none; } .wrapper{ position: relative; width: 627px; margin: 60px auto; } .search{ margin-right: 74px; border: 2px solid #ff5000; border-top-left-radius: 20px; border-bottom-left-radius: 20px; border-right: none; overflow: hidden; } .search input{ padding: 6px 0; text-indent: 10px; width: 551px; height: 24px; border: none; outline: none; } .btn{ position: absolute; top: 0; right: 0; font-size: 18px; font-weight: 700; width: 74px; height: 40px; border: none; border-top-right-radius: 20px; border-bottom-right-radius: 20px; background-color: #FF4200; color: #fff; outline: none; } .list{ display: none; position: absolute; top: 38px; left: 0; right: 74px; z-index: 100; border: 1px solid #ccc; background-color: #fff; } </style> </head> <body> <div class="wrapper"> <div class="search"> <input type="text"> </div> <button class="btn">搜索</button> <ul class="list"></ul> </div> <script> var oInput = document.getElementsByTagName('input')\[0\]; var oUl = document.getElementsByClassName('list')\[0\]; oInput.oninput = function () { var value = oInput.value; console.log(value) var oScript = document.createElement('script'); oScript.src = '[https://suggest.taobao.com/sug?code=utf-8&q=](https://suggest.taobao.com/sug?code=utf-8&q=)' \+ value + '&callback=cb'; document.body.appendChild(oScript); oScript.remove(); } function cb(data) { if (data.result.length > 0) { var str = ''; data.result.forEach(function (ele, index) { str += '<li>' + ele\[0\] + '</li>'; }); oUl.innerHTML = str; oUl.style.display = "block"; } else { oUl.style.display = "none"; } } </script> </body> </html>
CORS(Cross-Origin Resource Sharing,跨域资源共享)须要浏览器和后端同时支持。IE 8 和 9 须要经过 XDomainRequest 来实现。 浏览器会自动进行 CORS 通讯,实现CORS通讯的关键是后端。只要后端实现了 CORS,就实现了跨域。 服务端设置 Access-Control-Allow-Origin 就能够开启 CORS。 该属性表示哪些域名能够访问资源,若是设置通配符则表示全部网站均可以访问资源。跨域
该方式只能用于二级域名相同的状况下,好比 a.test.com 和 b.test.com 适用于该方式。只须要给页面添加 document.domain = 'test.com' 表示二级域名都相同就能够实现跨域。浏览器
这种方式一般用于获取嵌入页面中的第三方页面数据。一个页面发送消息,另外一个页面判断来源并接收消息。安全