function jsonp({ url, params, callback }) {
return new Promise((resolve, reject) => {
// 创建临时的scipt 标签,用于发起请求
const script = document.createElement('script')
// 绑定callback到window上,执行完回调函数后,移除script标签
window[callback] = data => {
resolve(data)
document.removeChild(script)
}
// 构造 GET 请求参数,key=value&callback=callback
const formatParams = { ...params, callback };
const requestParams = Object.keys(formatParams)
.reduce((acc, cur) => {
return acc.concat([`${cur}=${formatParams[cur]}`]);
}, [])
.join('&');
// 构造 GET 请求的 url 地址
const src = `${url}?${requestParams}`;
script.setAttribute('src', src);
document.body.appendChild(script);
})
}
// 调用时
jsonp({
url: 'https://xxx.xxx',
params: {id:2},
callback: 'fn',
})
//<script src='https://xxx.xxx.xx?id=2&callback=fn'><script>
console