由於瀏覽器出於安全考慮,有同源策略。也就是說,若是協議、域名或者端口有一個不一樣就是跨域,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' 表示二級域名都相同就能夠實現跨域。瀏覽器
這種方式一般用於獲取嵌入頁面中的第三方頁面數據。一個頁面發送消息,另外一個頁面判斷來源並接收消息。安全