UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

39 lines (37 loc) 1.32 kB
function jsonpRequest(_ref) { var url = _ref.url, callback = _ref.callback, errorCallback = _ref.errorCallback, _ref$timeout = _ref.timeout, timeout = _ref$timeout === void 0 ? 10000 : _ref$timeout; var callbackName = "jsonp_callback_".concat(Math.round(Date.now() + Math.random() * 100000)); var script = document.createElement('script'); // 定义全局回调函数 window[callbackName] = function (data) { delete window[callbackName]; document.body.removeChild(script); callback(data); }; // 处理错误 script.onerror = function () { delete window[callbackName]; document.body.removeChild(script); errorCallback === null || errorCallback === void 0 ? void 0 : errorCallback('请求失败'); }; // 设置超时 var timeoutId = setTimeout(function () { delete window[callbackName]; document.body.removeChild(script); errorCallback === null || errorCallback === void 0 ? void 0 : errorCallback('请求超时'); }, timeout); // 构建请求URL var formattedUrl = "".concat(url + (url.indexOf('?') >= 0 ? '&' : '?'), "callback=").concat(callbackName); script.src = formattedUrl; // 发送请求 document.body.appendChild(script); // 清理超时 return function () { clearTimeout(timeoutId); }; } export { jsonpRequest };