Open iwillwen opened 8 years ago
const JSONP = (function() { const global = window const defaultOptions = Object.freeze({ data: {}, callback: (data) => {} }) return (root, opts = defaultOptions) => { let url = root.trim().replace(/\?$/, '') + '?' const keys = Object.keys(opts.data) for (const key of keys) { url += `${safeEscape(key)}=${safeEscape(opts.data[key])}&` } const callbackName = `json${Math.random().toString(32).substr(2)}` global[callbackName] = function(data) { delete global[callbackName] opts.callback.call(JSONP, data) } url += `jsoncallback=${callbackName}` const script = document.createElement('script') script.src = url document.getElementsByTagName('body')[0].appendChild(script) } function safeEscape(str) { return encodeURIComponent(str.toString()) } })() JSONP('http://api.flickr.com/services/feeds/photos_public.gne', { data: { tags: 'cat', tagmode: 'any', format: 'json' }, callback(data) { console.log(data) } })
3 . https://gist.github.com/iwillwen/aa3ea7d24633a2f3864d another version: https://gist.github.com/iwillwen/b0ddaea384475d947540
@iwillwen 👍👍👍
3 . https://gist.github.com/iwillwen/aa3ea7d24633a2f3864d another version: https://gist.github.com/iwillwen/b0ddaea384475d947540