UNPKG

t-comm

Version:

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

39 lines (37 loc) 1.28 kB
function jsonpRequest(_a) { var url = _a.url, callback = _a.callback, errorCallback = _a.errorCallback, _b = _a.timeout, timeout = _b === void 0 ? 10000 : _b; 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 };