使用promise封装JSONP
本文最后更新于:2023年3月19日 晚上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const jsonp = ({ url, params, callbackName }) => { const generateUrl = () => { let dataSrc = ""; for (let key in params) { if (Object.prototype.hasOwnProperty.call(params, key)) { dataSrc += `${key}=${params[key]}&`; } } dataSrc += `callback=${callbackName}`; return `${url}?${dataSrc}`; }; return new Promise((resolve, reject) => { const scriptEle = document.createElement("script"); scriptEle.src = generateUrl(); document.body.appendChild(scriptEle); window[callbackName] = (data) => { resolve(data); document.removeChild(scriptEle); }; }); };
|