1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- /**
- * XMLHttpRequest工具类
- */
- module.exports = {
- /**
- * 封装原生的XMLHttpRequest
- * 使其用法像ajax
- *
- * url 请求链接【必须】
- * method 请求类型【默认 GET】
- * data 请求数据【POST时才有效】
- * timeout 超时时间【默认5000毫秒】
- * contentType 请求协议头 [['Content-type', application/x-www-form-urlencoded]]
- * dataType 返回数据类型【默认text】【arraybuffer blob document json text】
- * success 成功时回调
- * error 失败时回调
- * context 上下文环境
- * @author Pyden
- * @date 2019-03-21
- */
- ajax (params) {
- // 必要参数判断
- if (!params) {
- G.LogUtils.error('请求参数为空');
- return;
- }
- if (!params.url) {
- G.LogUtils.error('请求url为空');
- return;
- }
- // 默认参数补齐
- // success error context 不设置默认
- params.method = (params.method || 'GET').toUpperCase();
- params.data = params.data || {};
- params.timeout = params.timeout || 5000;
- params.contentType = params.contentType || [];
- params.dataType = params.dataType || '';
- // 对XHMHttp对象进行设置
- let xhr = cc.loader.getXMLHttpRequest();
- xhr.timeout = params.timeout;
- xhr.onload = e => {
- // 非200的都认为是失败
- // 假如服务器返回数据不规范,用了非200作为成功标志,这里会出现判断异常
- if (xhr.status == 200) {
- if (params.success) {
- if (params.context) {
- params.success.call(params.context, xhr.response);
- } else {
- params.success(xhr.response);
- }
- }
- } else {
- if (params.error) {
- if (params.context) {
- params.error.call(params.context, 'status:' + xhr.status);
- } else {
- params.error('status:' + xhr.status);
- }
- }
- }
- };
- xhr.ontimeout = e => {
- if (params.error) {
- if (params.context) {
- params.error.call(params.context, e);
- } else {
- params.error(e);
- }
- }
- };
- xhr.onerror = e => {
- if (params.error) {
- if (params.context) {
- params.error.call(params.context, e);
- } else {
- params.error(e);
- }
- }
- };
- xhr.open(params.method, params.url, true);
- for (const header of params.contentType) {
- xhr.setRequestHeader(header[0], header[1]);
- }
- xhr.responseType = params.dataType;
- if (params.method == 'POST') {
- xhr.send(params.data);
- } else {
- xhr.send();
- }
- }
- };
|