XMLHttpUtils.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * XMLHttpRequest工具类
  3. */
  4. module.exports = {
  5. /**
  6. * 封装原生的XMLHttpRequest
  7. * 使其用法像ajax
  8. *
  9. * url 请求链接【必须】
  10. * method 请求类型【默认 GET】
  11. * data 请求数据【POST时才有效】
  12. * timeout 超时时间【默认5000毫秒】
  13. * contentType 请求协议头 [['Content-type', application/x-www-form-urlencoded]]
  14. * dataType 返回数据类型【默认text】【arraybuffer blob document json text】
  15. * success 成功时回调
  16. * error 失败时回调
  17. * context 上下文环境
  18. * @author Pyden
  19. * @date 2019-03-21
  20. */
  21. ajax (params) {
  22. // 必要参数判断
  23. if (!params) {
  24. G.LogUtils.error('请求参数为空');
  25. return;
  26. }
  27. if (!params.url) {
  28. G.LogUtils.error('请求url为空');
  29. return;
  30. }
  31. // 默认参数补齐
  32. // success error context 不设置默认
  33. params.method = (params.method || 'GET').toUpperCase();
  34. params.data = params.data || {};
  35. params.timeout = params.timeout || 5000;
  36. params.contentType = params.contentType || [];
  37. params.dataType = params.dataType || '';
  38. // 对XHMHttp对象进行设置
  39. let xhr = cc.loader.getXMLHttpRequest();
  40. xhr.timeout = params.timeout;
  41. xhr.onload = e => {
  42. // 非200的都认为是失败
  43. // 假如服务器返回数据不规范,用了非200作为成功标志,这里会出现判断异常
  44. if (xhr.status == 200) {
  45. if (params.success) {
  46. if (params.context) {
  47. params.success.call(params.context, xhr.response);
  48. } else {
  49. params.success(xhr.response);
  50. }
  51. }
  52. } else {
  53. if (params.error) {
  54. if (params.context) {
  55. params.error.call(params.context, 'status:' + xhr.status);
  56. } else {
  57. params.error('status:' + xhr.status);
  58. }
  59. }
  60. }
  61. };
  62. xhr.ontimeout = e => {
  63. if (params.error) {
  64. if (params.context) {
  65. params.error.call(params.context, e);
  66. } else {
  67. params.error(e);
  68. }
  69. }
  70. };
  71. xhr.onerror = e => {
  72. if (params.error) {
  73. if (params.context) {
  74. params.error.call(params.context, e);
  75. } else {
  76. params.error(e);
  77. }
  78. }
  79. };
  80. xhr.open(params.method, params.url, true);
  81. for (const header of params.contentType) {
  82. xhr.setRequestHeader(header[0], header[1]);
  83. }
  84. xhr.responseType = params.dataType;
  85. if (params.method == 'POST') {
  86. xhr.send(params.data);
  87. } else {
  88. xhr.send();
  89. }
  90. }
  91. };