由於瀏覽器同源策略的限制,不容許ajax跨域請求vue
<img src='xxx'>
:用於打點統計<link href='xxx'>
:可使用CDN資源<script src='xxx'>
:能夠用於JSONP和CDN資源open /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dir
複製代碼
response.setHeader('Access-Control-Allow-Origin','http://a.com,http://b.com')
response.setHeader('Access-Control-Allow-Origin','X-Requested-With')
response.setHeader('Access-Control-Allow-Origin','PUT,POST,GET,DELETE,OPTIONS')
// 接收跨域的cookie
response.setHeader('Access-Control-Allow-Credentials','true')
複製代碼
function jsonp({url,params,cb}) {
return new Promise((resolve, reject) => {
let script = document.createElement('script');
window[cb] = function (params) {
resolve(params);
}
params = {...params,cb};
let arrs = [];
for(let key in params){
arrs.push(`${key}=${params[key]}`);
}
script.src = `${url}?${arrs.join('&')}`;
document.body.appendChild(script);
});
};
jsonp({
url: 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
params:{wd:'a'},
cb:'show'
}).then(data=>{
console.log('jsonp跨域請求的數據爲:',data);
});
複製代碼
jquery原代碼也是經過動態建立script標籤的形式實現跨越的jquery
$.ajax({
url: 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
type: 'get',
data: {wd:'a'},
dataType: 'jsonp', // 請求方式爲jsonp
jsonpCallback: "show", // 自定義回調函數名
success:function(){
},
error:function(){
}
});
複製代碼
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su', {
params: {wd:'a'},
jsonp: 'show'}).then((res) => {
console.log(res);
})
複製代碼
var xhr = new XMLHttpRequest()
xhr.open('GET','/api',false)
xhr.onreadystatechange = function (argument) {
if(xhr.readyState === 4){
if(xhr.status === 200){
alert(xhr.responseTest)
}
}
}
xhr.send(null)
複製代碼