Xhr.weapp.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. module.exports = class {
  3. constructor() {
  4. this.header = {};
  5. this.readyState = 4;
  6. this.status = 0;
  7. this.response = '';
  8. this.responseType = '';
  9. this.responseText = '';
  10. this.responseHeader = {};
  11. this.method = '';
  12. this.url = '';
  13. this.onerror = () => {};
  14. this.onreadystatechange = () => {};
  15. }
  16. getAllResponseHeaders() {
  17. let header = '';
  18. for (const key in this.responseHeader) {
  19. header += key + ':' + this.getResponseHeader(key) + '\r\n';
  20. }
  21. return header;
  22. }
  23. getResponseHeader(key) {
  24. return this.responseHeader[key];
  25. }
  26. setRequestHeader(key, value) {
  27. this.header[key] = value;
  28. }
  29. open(method, url) {
  30. this.method = method;
  31. this.url = url;
  32. }
  33. send(data) {
  34. wx.request({
  35. url: this.url,
  36. method: this.method,
  37. data: data,
  38. header: this.header,
  39. responseType: this.responseType,
  40. success: res => {
  41. this.status = res.statusCode;
  42. this.response = res.data;
  43. this.responseHeader = res.header;
  44. this.responseText = JSON.stringify(res.data);
  45. this.onreadystatechange();
  46. },
  47. fail: err => {
  48. this.onerror(err);
  49. }
  50. });
  51. }
  52. };