JSONP 通用函数封装
程序员文章站
2022-03-25 13:49:12
```javascript function jsonp({url, params, callback}) { return new Promise((resolve, reject) = { let script = document.createElement('script') // call ......
function jsonp({url, params, callback}) { return new promise((resolve, reject) => { let script = document.createelement('script') // callback 让服务器端调用,并且将数据传递进来 window[callback] = function (data) { resolve(data) document.body.removechild(script) } params = {...params, callback} const arr = [] for (let key in params) { arr.push(`${key}=${params[key]}`) } script.src = `${url}?${arr.join('&')}` document.body.appendchild(script) }) } function synchronize(urls) { return urls.map((url,i) => jsonp({url, params: {}, callback: 'show' + i})) } const ajurl = [ 'http://api.douban.com/v2/movie/in_theaters', 'http://api.douban.com/v2/movie/top250' ] promise.all(synchronize(ajurl)) .then(result => { for (let val of result) { console.log(val) } })