实现一个jsonp函数,仅需要支持jsonp(url)一种调用方式即可(仅有url一个传参),例如: jsonp('//t.alicdn.com/t/gettime?callback=cb').then(result=>console.dir(result))
//需使用promise
function jsonp(url) {
//在这里书写代码
return new Promise((resolve, reject) => {
let callbackName = `${url.split("?")[1].split("=")[1]}${Date.now()}`
url = url.split("?")[0] + `?${url.split("?")[1]}${Date.now()}`
let script = document.createElement('script')
script.src = url
window[callbackName] = (res) => {
delete window[callbackName]
document.body.removeChild(script)
if (res) {
resolve(res)
} else {
reject('没有返回数据')
}
}
script.addEventListener('error', () => {
delete window[callbackName]
document.body.removeChild(script)
reject('script资源加载失败')
}, false)
document.getElementsByTagName("body")[0].appendChild(script)
})
}
//调用
jsonp('//t.alicdn.com/t/gettime?callback=cb').then(result=>console.dir(result))