jsonp的简单实现
function jsonp(url, data) {
let params = '';
for (key in data) {
params += key + '=' + data[key] + '&';
}
url += '?' + params + 'callback=cbFn';
window.cbFn = function(data) {
res = data;
delete window.cbFn;
};
const script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
script.onload = () => {
document.body.removeChild(script);
};
const body = document.body.appendChild(script);
}
包装Promise的jsonp
function jsonp(url, params, callbackName) {
const geneateURL = (url, callbackName) => {
let res = '';
const keys = Object.keys(params);
for (let key of keys) {
res += `${key}=${params[key]}&`;
}
res = url + '?' + res + 'callback=' + callbackName;
return res;
};
return new Promise((resolve, reject) => {
callbackName = callbackName || Math.random().toString().replace('.', '');
const script = document.createElement('script');
const genURL = geneateURL(url, callbackName);
script.setAttribute('src', genURL);
window[callbackName] = (data) => {
resolve(data);
delete window[callbackName];
document.body.removeChild(script);
};
document.body.appendChild(script);
});
}