Created
December 20, 2016 02:56
-
-
Save leizongmin/4cb1becffa52956ad9dc3008c7e34a43 to your computer and use it in GitHub Desktop.
简单JSONP请求器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
帅