一、演示同源策略
首先找到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>点我获取数据</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。
点击按钮后我们可以看到获得的数据,同源情况下获取数据成功。
3.jpg
将$.ajax()函数中的url更改成
url:'//b.com/ajax.js',
刷新a.com/ CroosOrigin.html后点击按钮,弹出获取数据失败,查看控制台:
出错-控制台.jpg
受同源策略限制,a.com和b.com非同源,所以a.com无法请求b.com下的数据。
二、跨域
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.`)
即可规避由同源策略带来的限制。点击按钮,数据能正常显示。