由于浏览器同源策略的限制,不容许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)
复制代码