实现 jsonp
Sunny-117 opened this issue · comments
实现 jsonp
const jsonp = (url, params, cbName) => {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
window[cbName] = (data) => {
resolve(data);
document.body.removeChild(script);
}
params = {...params, callback: cbName};
const arr = Object.keys(params).map(key => `${key}=${params[key]}`);
script.src = `${url}?${arr.join('&')}`;
document.body.appendChild(script);
})
}
function jsonp(url, jsonpCallback, success) {
let script = document.createElement('script');
script.src = url;
script.async = true;
window[jsonpCallback] = function(data) {
success && success(data);
};
document.body.appendChild(script);
}