一蒋困、演示同源策略
首先找到C盤下的Windows/System32/drivers/etc下的hosts文件,用筆記本打開,添加一條ip和域名
127.0.0.1 localhost a.com b.com
1.jpg
將a.com和b.com都指向本機氓涣。然后打開XAMPP,開啟Apache和MySQL陋气,搭建本地服務器劳吠。
2.jpg
在本機的XAMPP下的 htdocs文件夾下寫代碼 CroosOrigin.html
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><title></title> </head>
<body>
<button>點我獲取數(shù)據(jù)</button>
<div class="data"></div>
<script src='http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js'></script>
<script type="text/javascript">
$('button').on('click',function(){
$.ajax({
url:'//a.com/ajax.js', //或直接寫ajax.js
dataType:'text',
type:'get',
success:function(data){
$('.data').text(data);
},
error:function(){
alert('獲取失敗');
}
});
})
</script>
</body></html>
ajax.js中的代碼就一行
this is ajax.js data.
然后瀏覽器打開a.com/ CroosOrigin.html。
點擊按鈕后我們可以看到獲得的數(shù)據(jù)巩趁,同源情況下獲取數(shù)據(jù)成功痒玩。
3.jpg
將$.ajax()函數(shù)中的url更改成
url:'//b.com/ajax.js',
刷新a.com/ CroosOrigin.html后點擊按鈕,彈出獲取數(shù)據(jù)失敗议慰,查看控制臺:
出錯-控制臺.jpg
受同源策略限制蠢古,a.com和b.com非同源,所以a.com無法請求b.com下的數(shù)據(jù)别凹。
二便瑟、跨域
JOSNP
將a.com/ CroosOrigin.html下的代碼改成如下:
function addScriptTag(src) {
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.src = src;
document.body.appendChild(script);
}
$('button').on('click',function(){
addScriptTag('http://b.com/ajax.js?callback=foo');
});
function foo(data) {
$('.data').text(data);
};
將ajax.js中的代碼改為如下:
foo(`this is ajax.js data.`)
即可規(guī)避由同源策略帶來的限制。點擊按鈕番川,數(shù)據(jù)能正常顯示。