Last active
February 9, 2018 03:44
-
-
Save bravelincy/121d8e3619ba1f9e2835f74382d76eba 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 merge () { | |
var args = [].slice.call(arguments) | |
var obj = {} | |
args.forEach(function (arg) { | |
if (typeof arg === 'object' && arg) { | |
for (var k in arg) { | |
obj[k] = arg[k] | |
} | |
} | |
}) | |
return obj | |
} | |
function serialize (obj) { | |
var spans = [] | |
for (var k in obj) { | |
spans.push(k + '=' + obj[k]) | |
} | |
return spans.join('&') | |
} | |
function jsonp (options) { | |
var script = document.createElement('script') | |
var callbackFn = options.callback || ('jsonpCallback' + Math.random()).replace('0.', '') | |
var params = merge({ | |
callback: callbackFn | |
}, options.params) | |
var query = serialize(params) | |
var url = options.url | |
url += ~url.indexOf('?') ? '&' : '?' + query | |
script.onload = function () { | |
delete window[callbackFn] | |
document.head.removeChild(script) | |
} | |
script.onerror = function () { | |
script.onload() | |
options.faild && options.faild() | |
} | |
script.src = url | |
window[callbackFn] = options.success | |
document.head.appendChild(script) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: