欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JSONP 通用函数封装

程序员文章站 2022-06-30 23:43:14
```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)
          }
        })