12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import config from "../config/index.js";
- import { showLoadingToast, showToast, closeToast } from "vant";
- import "vant/lib/toast/style/index";
- function getdata(data) {
- let text = "";
- for (const key in data) {
- text += key + "=" + data[key] + "&";
- }
- text ? (text = "?" + text) : "";
- text = text.replace(/&$/, "");
- return text;
- }
- export default function (ori) {
- let baseurl = config.base[ori.urlType || "ajax"];
- let url = baseurl + ori.url;
- let isEnd = false;
- let noToast = ori.noToast;
- let defaultErrorToast = ori.errorToast || "请求失败!";
- let time = setTimeout(() => {
- clearTimeout(time);
- !isEnd &&
- !ori.noLoad &&
- showLoadingToast({
- message: "加载中...",
- forbidClick: true,
- duration: 0,
- });
- }, 300);
- return new Promise((resolve, reject) => {
- var xhttp;
- if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
- else if (window.ActiveXObject)
- xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
- let method = ori.method.toUpperCase();
- if (method === "GET") url += getdata(ori.data || {});
- xhttp.open(method, url, true);
- const headers = Object.keys(ori.header);
- for (let i = 0; i < headers.length; i++) {
- let key = headers[i];
- if (key === 'contentType') {
- key = 'Content-Type';
- ori.header[key] = ori.header['contentType']
- }
- xhttp.setRequestHeader(key, ori.header[key]);
- }
- if (ori.isFormData) {
- xhttp.send(ori.data);
- } else {
- xhttp.setRequestHeader("Content-type", 'application/json');
- method === "GET" ? xhttp.send() : xhttp.send(JSON.stringify(ori.data));
- }
- xhttp.onreadystatechange = function () {
- if (this.readyState != 4) return;
- isEnd = true;
- closeToast();
- if (this.status != 200) {
- let t = JSON.parse(this.responseText || "{}");
- !noToast && showToast(t.message || defaultErrorToast);
- reject(t);
- return;
- }
- let data = {};
- try {
- data =
- this.responseText !== "null"
- ? JSON.parse(this.responseText || "{}")
- : {};
- } catch (err) {
- !noToast && showToast(defaultErrorToast);
- console.error(err);
- reject(err);
- }
- if (data.code === 0 || ori.next) resolve(data.data || data);
- else reject(data);
- };
- });
- }
|