跨域概念
同源策略是瀏覽器上為安全性考慮實施的非常重要的安全機制跨新。Ajax默認是能獲取同源的數(shù)據(jù),對于非同源的數(shù)據(jù)Ajax默認是不能獲取到的赘被。什么叫同源呢肖揣,同源就是兩個相互交互的地址的協(xié)議,端口许饿,域名三者都一樣;比如有一個頁面,它的地址為http://www.ko.com/dir/page.html這個網(wǎng)址秽晚,在這個網(wǎng)址中要去獲取服務器的數(shù)據(jù)筒愚,獲取數(shù)據(jù)的地址如下:
#URL 結果 原因
https://www.ko.com/dir/page.html 不同源 協(xié)議不同,一個是http巢掺,一個是http
http://www.ko1.com/dir/page.html 不同源 域名不同,一個是ko陆淀,一個是ko1
http://www.ko.com:82/dir/page.html 不同源 端口不同,一個是80楚堤,一個是82
http://www.ko.com/dir1/page.html 同源
如果獲取非同源數(shù)據(jù)含懊,就會報以下異常:
Failed to load https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=%E8%B1%86: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
如果我們想要獲取跨域的數(shù)據(jù),我們該怎么辦呢岔乔?
可以通過script的src方式,也可以使用ajax設置數(shù)據(jù)類型為jsonp
#方式一
<script type='text/javascript'>
function cb(data){
console.log(data);
}
</script>
<script type='text/javascript' src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=dd&callback=cb"></script>
#方式二
$.ajax({
url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",
data:{wd:"豆"},
success:function(data){
console.log(data);
},
dataType:"jsonp",
jsonp:"cb"
})