request.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import config from "../config/index.js";
  2. import { showLoadingToast, showToast, closeToast } from "vant";
  3. import "vant/lib/toast/style/index";
  4. function getdata(data) {
  5. let text = "";
  6. for (const key in data) {
  7. text += key + "=" + data[key] + "&";
  8. }
  9. text ? (text = "?" + text) : "";
  10. text = text.replace(/&$/, "");
  11. return text;
  12. }
  13. export default function (ori) {
  14. let baseurl = config.base[ori.urlType || "ajax"];
  15. let url = baseurl + ori.url;
  16. let isEnd = false;
  17. let noToast = ori.noToast;
  18. let time = setTimeout(() => {
  19. clearTimeout(time);
  20. !isEnd &&
  21. !ori.noLoad &&
  22. showLoadingToast({
  23. message: "加载中...",
  24. forbidClick: true,
  25. duration: 0,
  26. });
  27. }, 300);
  28. return new Promise((resolve, reject) => {
  29. var xhttp;
  30. if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
  31. else if (window.ActiveXObject)
  32. xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
  33. let method = ori.method.toUpperCase();
  34. if (method === "GET") url += getdata(ori.data || {});
  35. xhttp.open(method, url, true);
  36. xhttp.setRequestHeader(
  37. "Content-type",
  38. ori.header
  39. ? ori.header.contentType || "application/json"
  40. : "application/json"
  41. );
  42. xhttp.setRequestHeader(
  43. "Authorization",
  44. ori.header && ori.header.Authorization
  45. );
  46. method === "GET" ? xhttp.send() : xhttp.send(JSON.stringify(ori.data));
  47. xhttp.onreadystatechange = function () {
  48. if (this.readyState != 4) return;
  49. isEnd = true;
  50. closeToast();
  51. if (this.status != 200) {
  52. let t = JSON.parse(this.responseText || "{}");
  53. !noToast && showToast(t.message || "请求失败 " + this.status);
  54. reject(t);
  55. return;
  56. }
  57. let data = {};
  58. try {
  59. data =
  60. this.responseText !== "null"
  61. ? JSON.parse(this.responseText || "{}")
  62. : {};
  63. } catch (err) {
  64. !noToast && showToast("请求失败");
  65. console.error(err);
  66. reject(err);
  67. }
  68. if (data.code === 0 || ori.next) resolve(data.data);
  69. else reject(data);
  70. };
  71. });
  72. }