JSONP

Suikoigia發表於2020-10-05
const jsonp = ({url, params, callbackName}) => {
  const generateUrl = () => { // 拼接url
    let dataStr = ``
    for (let key in params) {
      dataStr += `${key}=${params[key]}&`
    }
    dataStr += `callbackName=${callbackName}`
    return `${url}?${dataStr}`
  }

  return new Promise((resolve, reject) => {
    const scriptEle = document.createElement('script')
    scriptEle.src = generateUrl()
    document.body.appendChild(scriptEle)
    window[callbackName] = data => { // 掛載到window
      resolve(data)
      document.body.removeChild(scriptEle) // 資料接收完畢,刪除script元素
    }
  })
}

相關文章