1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 function jsonp(url, param, cb) { // 构造query let query = url.indexOf('?') === -1 ? '?' : '&' for (let key of Object.keys(param)) { query += key + '=' + param[key] + '&' } // 随机回调函数名 let random = Math.random().toString().replace('.', '') let cbname = 'cb' + random query += 'callback=' + cbname let script = document.createElement('script') script.setAttribute("type", "text/javascript"); script.src = url + query window[cbname] = (params) => { cb(params) document.removeChild(script) } // 后添加 因为一经添加立马请求 document.body.appendChild(script) } let url = 'https://XXXXXXX' jsonp(url, {}, (val)=>{console.log(val)})
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 const jsonp = ({ url, params, callbackName } ) => { const generateURL = () => { let dataStr = '' ; for (let key in params) { dataStr += `${key} =${params[key]} &` ; } dataStr += `callback=${callbackName} ` ; return `${url} ?${dataStr} ` ; }; return new Promise ((resolve, reject ) => { callbackName = callbackName || Math .random().toString.replace(',' , '' ); let scriptEle = document .createElement('script' ); scriptEle.src = generateURL(); document .body.appendChild(scriptEle); window [callbackName] = (data ) => { resolve(data); document .body.removeChild(scriptEle); } }); }
ref https://juejin.cn/post/6844904100035821575 https://www.cnblogs.com/zzc5464/p/jsonp.html