UNPKG

tsp-component

Version:

提供多端和react版本的UI组件

67 lines (66 loc) 2.43 kB
import { urlEncode } from '../util/router'; function ajax(cfg) { var method = (cfg.type || 'POST').toUpperCase(); var data = cfg.contentType !== 'application/json' || method === 'GET' ? urlEncode(cfg.data) : JSON.stringify(cfg.data); var url = method === 'GET' && data ? cfg.url + '?' + data : cfg.url; var async = !cfg.sync; var dataType = cfg.dataType ? cfg.dataType : 'json'; var xhr = new XMLHttpRequest(); xhr['url'] = url; xhr.timeout = cfg.timeout ? cfg.timeout : 15000; if (cfg.onTimeout) { xhr.ontimeout = cfg.onTimeout; } if (cfg.onProgress) { this.xhr.upload.onprogress = function (e) { if (e.lengthComputable) { cfg.onProgress(e.loaded, e.total); } }; } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { var status_1 = xhr.status; var xhrdata = void 0; if ((status_1 >= 200 && status_1 < 300) || status_1 === 304) { switch (dataType.toLowerCase()) { case 'xml': xhrdata = xhr.responseXML; break; case 'json': xhrdata = JSON && JSON.parse ? JSON.parse(xhr.responseText) : eval('(' + xhr.responseText + ')'); break; default: xhrdata = xhr.responseText; } if (cfg.success) { cfg.success(xhrdata, xhr); } } else { if (cfg.error) { cfg.error(xhr); } } if (cfg.complete) { cfg.complete(xhr); } } }; xhr.open(method, url, async); if (method === 'GET') { xhr.setRequestHeader('Content-type', 'text/plain; charset=UTF-8'); } else { var header = cfg.contentType ? cfg.contentType : 'application/x-www-form-urlencoded; charset=UTF-8'; if (cfg.customHeader) { Object.keys(cfg.customHeader).forEach(function (value) { xhr.setRequestHeader(value, cfg.customHeader[value]); }); } xhr.setRequestHeader('Content-type', header); } xhr.send(data); return xhr; } export default ajax;