一篇写的很通俗易懂的jsonp文章
https://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html
在Vue中封装的jsonp方法
@param { string } url – url地址
@param { object } data – 传参配置项(url传参配置)
@param { object } option – 传参配置项(jsonp回调名称)
import originJsonp from 'jsonp'
export default function jsonp(url, data, option) {
url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)
return new Promise((resolve, reject) => {
originJsonp(url, option, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}
export function param(data) {
let url = ''
for (var k in data) {
let value = data[k] !== undefined ? data[k] : ''
url += '&' + k + '=' + encodeURIComponent(value)
}
return url ? url.substring(1) : ''
}
以请求QQ音乐接口为例
function getTopList() {
const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_myqq_toplist.fcg'
const data = Object.assign({}, {
g_tk: 1928093487,
inCharset: 'utf-8',
outCharset: 'utf-8',
notice: 0,
format: 'jsonp',
uin: 0,
needNewCode: 1,
platform: 'h5'
})
return jsonp(url, data, 'jsonpCallback')
}