重點:
跨域並不是請求發不出去,請求能發出去,服務端能收到請求並正常返回結果,只是結果被瀏覽器攔截了。
跨域方法:
1.JSONP:只能GET,js創建script
2.CORS:IE10以上支持
3.window.postMessage:HTML5方法,應用於主頁面和iframe之間的數據傳遞
//頁面向子頁面傳遞:
//主頁面
<iframe id="ifm" src="http://localhost:8080/" width="800" height="500"></iframe>
<script>
document.getElementById('ifm').onload = e=>{
e.target.contentWindow.postMessage({info:'這是來自主頁面的信息'},'*')
}
</script>
//子頁面
<script>
window.onmessage = (event) => {
console.log(event)
}
</script>
//子頁面向主頁面傳遞
//主頁面
<iframe id="ifm" src="http://localhost:8080/" width="800" height="500"></iframe>
<script>
window.onmessage = (event) => {
console.log(event)
}
</script>
//子頁面
<script>
top.postMessage({info:'這是來自子頁面的信息'},'*')
</script>
//子頁面
4.web socket
5.document.domain
6.window.name