Skip to content

Instantly share code, notes, and snippets.

@leizongmin
Created December 20, 2016 02:56
Show Gist options
  • Save leizongmin/4cb1becffa52956ad9dc3008c7e34a43 to your computer and use it in GitHub Desktop.
Save leizongmin/4cb1becffa52956ad9dc3008c7e34a43 to your computer and use it in GitHub Desktop.
简单JSONP请求器
function jsonp(url, f) {
return new Promise((resolve, reject) => {
f = f || 'callback';
const n = `_jsonpCb` + Date.now() + parseInt(Math.random() * 100000, 10);
window[n] = (data) => {
resolve(data);
document.body.removeChild(s);
};
const s = document.createElement('script');
s.onerror = (e) => reject(e);
s.type = 'text/javascript';
s.src = url + (url.indexOf('?') === -1 ? '?' : '&') + `${ f }=${ n }`;
document.body.appendChild(s);
});
}
// 测试
jsonp('https://www.reddit.com/r/aww.json', 'jsonp')
.then(d => console.log('ok', d))
.catch(e => console.error('error', e));
@musclejack
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment