HttpUtil.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. export class HttpUtil {
  2. static get(url: string, callback: (statusCode: number, resp: object | null) => any) {
  3. let xhr = new XMLHttpRequest();
  4. xhr.timeout = 2000;
  5. xhr.open("GET", url);
  6. xhr.onreadystatechange = () => {
  7. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
  8. let resp = null;
  9. try {
  10. if (xhr.responseText != "") {
  11. resp = JSON.parse(xhr.responseText);
  12. }
  13. } catch (e) {
  14. }
  15. callback && callback(1, resp);
  16. }
  17. };
  18. xhr.onerror = () => {
  19. callback && callback(0, null);
  20. };
  21. xhr.ontimeout = () => {
  22. callback && callback(0, null);
  23. };
  24. xhr.send();
  25. return xhr;
  26. }
  27. static post(url: string, callback: (statusCode: boolean, resp: any | null) => any, data: object | string | null) {
  28. let xhr = new XMLHttpRequest();
  29. xhr.timeout = 2000;
  30. xhr.open("POST", url, true);
  31. xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  32. xhr.onreadystatechange = () => {
  33. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
  34. let resp = null;
  35. try {
  36. if (xhr.responseText != "") {
  37. resp = JSON.parse(xhr.responseText);
  38. }
  39. } catch (e) {
  40. }
  41. callback && callback(true, resp);
  42. }
  43. };
  44. xhr.onerror = (mgs) => {
  45. console.log('网络错误');
  46. callback && callback(false, null);
  47. };
  48. xhr.ontimeout = (mgs) => {
  49. console.log('网络超时');
  50. callback && callback(false, null);
  51. };
  52. if (data) {
  53. let text = typeof (data) == "string" ? data : JSON.stringify(data);
  54. xhr.send(text);
  55. return xhr;
  56. }
  57. xhr.send();
  58. return xhr;
  59. }
  60. }