UNPKG

vivo-ui

Version:

vivo ui component lib for vue

70 lines (61 loc) 1.96 kB
import _Object$keys from 'babel-runtime/core-js/object/keys'; import _Object$assign from 'babel-runtime/core-js/object/assign'; function formatParams(params) { params = _Object$assign({ __timestamp__: Date.now() }, params); return _Object$keys(params).map(function (value) { return value + '=' + params[value]; }).join('&'); } function getStatus(code) { switch (code) { case 200: return 'success'; case 304: return 'notmodified'; default: return 'error'; } } function index (options) { var xhr = new window.XMLHttpRequest(); var params = formatParams(options.params); var async = options.async !== undefined ? options.async : true; var type = (options.type || 'get').toLowerCase(); var completed = void 0; xhr.timeout = options.timeout || 0; xhr.responseType = options.dataType || 'json'; xhr.onreadystatechange = function () { if (xhr.readyState === 4) { var status = getStatus(xhr.status); completed = true; if (status === 'success') { options.success && options.success(xhr.response, status, xhr); } else { options.error && options.error(xhr, status, xhr.statusText); } options.complete && options.complete(status, xhr); } }; xhr.ontimeout = function () { options.error && options.error(xhr, 'timeout', xhr.statusText); options.complete && options.complete('timeout', xhr); }; xhr.abort = function () { if (!completed) { xhr.abort(); options.error && options.error(xhr, 'abort', xhr.statusText); options.complete && options.complete('abort', xhr); } }; if (type === 'get') { xhr.open(type, options.url + ('' + (options.url.indexOf('?') === -1 ? '?' : '&')) + params, async); xhr.send(null); } else { xhr.open(type, options.url, async); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(params); } } export default index;