Xhr.weapp.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. module.exports = class {
  3. constructor() {
  4. this.UNSENT = 0;
  5. this.OPENED = 1;
  6. this.HEADERS_RECEIVED = 2;
  7. this.LOADING = 3;
  8. this.DONE = 4;
  9. this.header = {};
  10. this.readyState = this.DONE;
  11. this.status = 0;
  12. this.response = '';
  13. this.responseType = '';
  14. this.responseText = '';
  15. this.responseHeader = {};
  16. this.method = '';
  17. this.url = '';
  18. this.onabort = () => {};
  19. this.onprogress = () => {};
  20. this.onerror = () => {};
  21. this.onreadystatechange = () => {};
  22. this.requestTask = null;
  23. }
  24. getAllResponseHeaders() {
  25. let header = '';
  26. for (const key in this.responseHeader) {
  27. header += key + ':' + this.getResponseHeader(key) + '\r\n';
  28. }
  29. return header;
  30. }
  31. getResponseHeader(key) {
  32. return this.responseHeader[key];
  33. }
  34. setRequestHeader(key, value) {
  35. this.header[key] = value;
  36. }
  37. open(method, url) {
  38. this.method = method;
  39. this.url = url;
  40. }
  41. abort() {
  42. if (!this.requestTask) {
  43. return;
  44. }
  45. this.requestTask.abort();
  46. this.status = 0;
  47. this.response = undefined;
  48. this.onabort();
  49. this.onreadystatechange();
  50. }
  51. send(data) {
  52. this.requestTask = wx.request({
  53. url: this.url,
  54. method: this.method,
  55. data: data,
  56. header: this.header,
  57. responseType: this.responseType,
  58. success: res => {
  59. this.status = res.statusCode;
  60. this.response = res.data;
  61. this.responseHeader = res.header;
  62. this.responseText = JSON.stringify(res.data);
  63. this.requestTask = null;
  64. this.onreadystatechange();
  65. },
  66. fail: err => {
  67. this.requestTask = null;
  68. this.onerror(err);
  69. }
  70. });
  71. this.requestTask.onProgressUpdate(res => {
  72. const event = {
  73. lengthComputable: res.totalBytesExpectedToWrite !== 0,
  74. loaded: res.totalBytesWritten,
  75. total: res.totalBytesExpectedToWrite
  76. };
  77. this.onprogress(event);
  78. });
  79. }
  80. };