xhr.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. namespace xhr {
  2. export class Req {
  3. private doneFns = [];
  4. private errorFns = [];
  5. public constructor(private xhr: XMLHttpRequest) {
  6. xhr.onload = () => {
  7. var text = xhr.responseText,
  8. status = xhr.status;
  9. this.doneFns.forEach((fn) => {
  10. fn(text, status);
  11. });
  12. };
  13. xhr.onerror = () => {
  14. this.errorFns.forEach((fn) => fn());
  15. };
  16. }
  17. public onDone(fn: (data: string, status: number) => void) {
  18. this.doneFns.push(fn);
  19. return this;
  20. }
  21. public onError(fn: () => void) {
  22. this.errorFns.push(fn);
  23. return this;
  24. }
  25. public withHeader(k: string, v: string) {
  26. this.xhr.setRequestHeader(k, v);
  27. return this;
  28. }
  29. public sendJSON(data: any) {
  30. this.withHeader('Content-Type', 'application/json;charset=utf8');
  31. this.xhr.send(JSON.stringify(data));
  32. return this;
  33. }
  34. public send(data?: string) {
  35. this.xhr.send(data);
  36. return this;
  37. }
  38. }
  39. export var create = (method: string, url: string) => {
  40. var xhr = new XMLHttpRequest();
  41. xhr.open(method, url, true);
  42. return new Req(xhr);
  43. };
  44. export var get = (url: string) => {
  45. return create('GET', url);
  46. }
  47. export var post = (url: string) => {
  48. return create('POST', url);
  49. }
  50. }