常見的跨域解決方案以及原理
阿新 • • 發佈:2018-11-05
一、JSONP(適用於單項跨域請求)
原理:因為瀏覽器對script不存在同源策略,所以script可以跨域請求外部資源,返回的資料是json格式。
缺點:1、只能傳送get請求,無法傳送post請求
2、無法判斷請求成功還是失敗
二、porxy代理
原理:讓代理伺服器請求目標地址,因為請求是在服務端進行的,在服務端不存在跨域,從而解決跨域問題
實現:將原地址繫結在代理伺服器下,讓代理伺服器傳送請求。
三、document.domain
通過js強制改變document.domain為基礎主域
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <iframe src="domain2.html"></iframe> <script> document.domain="127.0.0.1"; var user="lirunhui"; </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>domain1</h1> <h2></h2> <script> document.domain="127.0.0.1"; console.log(window.parent.user); </script> </body> </html>
4、postMessage
在我部落格裡有篇專門說的postMessage。
postMessage(data,url); 例子:win=window.open("http://jhssdemo.duapp.com/demo/h5_postmessage/win.html"); win.postMessage('GoogLucky',"http://jhssdemo.duapp.com/"); 或者傳送給ifram ifram物件.postMessage(data,url); windows.addEventListener("message",function(e)//接受資料 { console.log(e.origin,e.data); alert("有資料來了"); } );