参考答案:
JSONP 核心原理:script 标签不受同源策略约束,所以可以用来进行跨域请求,优点是兼容性好,但是只能用于 GET 请求;
1const jsonp = ({ url, params, callbackName }) => { 2 const generateUrl = () => { 3 let dataSrc = '' 4 for (let key in params) { 5 if (params.hasOwnProperty(key)) { 6 dataSrc += `${key}=${params[key]}&` 7 } 8 } 9 dataSrc += `callback=${callbackName}` 10 return `${url}?${dataSrc}` 11 } 12 return new Promise((resolve, reject) => { 13 const scriptEle = document.createElement('script') 14 scriptEle.src = generateUrl() 15 document.body.appendChild(scriptEle) 16 window[callbackName] = data => { 17 resolve(data) 18 document.removeChild(scriptEle) 19 } 20 }) 21}
最近更新时间:2022-05-22