Skip to content

Instantly share code, notes, and snippets.

@Jesseyx
Created September 22, 2016 09:16
Show Gist options
  • Save Jesseyx/983f8857114f89f2a21dacb6d26581b8 to your computer and use it in GitHub Desktop.
Save Jesseyx/983f8857114f89f2a21dacb6d26581b8 to your computer and use it in GitHub Desktop.
A jsonp function
function jsonp(options) {
options = options || {};
if (!options.url || !options.jsonp) {
throw new Error('参数不合法');
}
options.data = options.data || {};
// 创建 script
var callbackName = ('jsonp_' + Math.random()).replace('.', '');
options.data[options.jsonp] = callbackName;
var params = formatParams(options.data);
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
head.appendChild(script);
// 创建回调
window[callbackName] = function (json) {
clearTimeout(script._timeId);
script._timeId = null;
head.removeChild(script);
window[callbackName] = null;
delete window[callbackName];
options.success && options.success(json);
}
// 发送请求
script.src = options.url.indexOf('?') > 0 ? (options.url + '&' + params) : (options.url + '?' + params);
// 超时处理
if (options.timeout) {
script._timeId = setTimeout(function () {
script._timeId = null;
head.removeChild(script);
window[callbackName] = null;
delete window[callbackName];
options.fail && options.fail({ message: '请求超时' });
}, options.timeout);
}
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
return arr.join('&');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment