1.同源策略是瀏覽器的一個安全功能,兩個頁面的協議,端口和域名都相同,則兩個頁面具備相同的源。
例:https://segmentfault.com:81/u/mount_chan
其中https爲協議,segmentfault爲域名,81爲端口號,三者必須一致的兩個頁面才能成爲同源,才能夠進行ajax請求前端
URL | status | reason |
---|---|---|
https://segmentfault.com:81/u/mount_chan2 | success | 同源 |
https://segmentfault.com:80/u/mount_chan | fail | (80)不一樣端口 |
http://segmentfault.com:81/u/mount_chan | fail | (http)不一樣協議 |
https://baidu.com:81/u/mount_chan | fail | (baidu)不一樣域名 |
2.因爲同源策略的影響,咱們在實際開發中想要調取其餘協議,如百度地圖,定位信息等,這些都會限制,所以咱們要想實現功能,就必須用到跨域的方法,這一塊我常常用jsonp進行跨域請求。vue
$('#a').click(function(){ var frame = document.createElement('script'); frame.src = 'https://segmentfault.com/write?freshman=1&callback=mount_chan'; $('body').append(frame); });
其中callback裏面裝的是返回的數據,再看以下:jquery
$('#a').click(function(){ var frame = document.createElement('script'); frame.src = 'https://segmentfault.com/write?freshman=chan&callback=mount_chan'; $('body').append(frame); }); function mount_chan(res){ console.log(res.message) }
咱們聲明瞭一個mount_chan函數,若是服務端接口到get請求,返回的是mount_chan({message:'hello',chan:chen}),這樣的話就能夠在服務端把數據經過函數執行傳參的方式實現數據傳遞。如此即可實現jsonp跨域請求。callback在前端中聲明傳給後端的函數名字,後端接收以後將數據在傳給前端。ajax
npm install vue-jsonp --save
import vueJsonp from 'vue-jsonp' Vue.use(vueJsonp)
let obj = { 'location':item.point.lat+','+item.point.lng, 'output':'json', 'ak':'\*\*\*' } this.$jsonp('https://api.map.baidu.com/geocoder/v2/', obj).then(res => { console.log(res) this. }).catch(err => { console.log(err) })