Xhr.weapp.js 1.2 KB

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