+
95
-

回答

axios自己写一个,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue@2.6.1.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/axios-0.18.js"></script>
</head>
<body>
<div id="app">
请输入关键字:<input type="text" v-model="keyword" @keyup="sendJsonP(keyword)">
<ul>
<li v-for="r in result">{{r}}</li>
</ul>
</div>
<script>

window.onload = function () {
axios.jsonp = (url, data)=> {
if (!url)
throw new Error('url is necessary')
const callback = 'CALLBACK' + Math.random().toString().substr(9, 18)
const JSONP = document.createElement('script')
JSONP.setAttribute('type', 'text/javascript')

const headEle = document.getElementsByTagName('head')[0]

let ret = '';
if (data) {
if (typeof data === 'string')
ret = '&' + data;
else if (typeof data === 'object') {
if ('jsonp' in data){

ret += '&' + data.jsonp + '=' + callback;
}else{
ret += '&callback=' + callback;
}
for (let key in data)
ret += '&' + key + '=' + encodeURIComponent(data[key]);
}
ret += '&_time=' + Date.now();
}
JSONP.src = `${url}${ret}`;
// JSONP.src = `${url}?callback=${callback}${ret}`;
return new Promise((resolve, reject) => {
window[callback] = r => {

resolve({data:r})
headEle.removeChild(JSONP)
delete window[callback]
}
headEle.appendChild(JSONP)
})

}

new Vue({
el: '#app',
data: {
keyword: '',
result: ''
},
methods: {
sendJsonP(keyword) {
let url = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web';
axios.jsonp (url, {

wd: keyword
,
jsonp: 'cb'//jsonp默认是callback,百度缩写成了cb,所以需要指定下 }
}).then(res => {
console.log(res);
if (res.data.g) {
this.result = res.data.g.map(x => x['q']);
} else {
this.result = [];
}
});
}
}
});
}
</script>
</body>
</html>

或者使用vue-jsonp插件

npm install vue-jsonp --save
在vue cli项目main.js中添加

import { VueJsonp } from 'vue-jsonp' 
Vue.use(VueJsonp)

在任意.vue文件中使用

// 因为引入了vue-jsonp,所以可以直接使用this.$jsonp, Vue.use(VueJsonp)方法里把$jsonp赋给vue原型了:Vue.prototype.$jsonp = jsonp

this.$jsonp('https://api.map.baidu.com/geocoder/v2/?callback=renderReverse&output=json&pois=1' , {
ak: 'ZwTVu16RLXjhW7FHDjYt5HfMnR1dhFpR',
location: e.point.lat + ',' + e.point.lng
}).then((res)=>{
 console.log(res)
})



网友回复

我知道答案,我要回答