vue中axios如何进行jsonp请求?
网友回复
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) })
如果对uniapp打包生成的ios安装包ipa进行混淆加密加壳保护?
局域网中多台电脑如何不插拔usb实现鼠标键盘共享?
nc如何实现反向shell?
ai如何根据别人朋友圈拍摄的照片获取经纬度信息?
如何将llama3接入Siri?
js如何获取浏览器canvas指纹?
如何使用用js写一个字符串位移加密传给后端php解密?
Selenium打开网页模拟点击页面按钮的e.trusted是true吗?
听说Gemini 1.5 Flash能根据你的录屏操作网页视频生成Selenium代码?
coze Webhook URL发送触发器报错:{"code":41001004,"data":{"items":[]},"items":[],"message":"RecordNotFound:Pl