1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| interface AjaxConfig { url: string; type?: "get" | "head" | "delete" | "option" | "post" | "patch" | "put"; dataType?: "json" | "jsonp" | "text" | "xml"; data?: object; jsonp?: string; jsonpCallBack?: string; async?: boolean; success?: Function; }
class Ajax { private requestParams: string = ""; private requestSetting: AjaxConfig = { url: "", type: "get", data: {}, dataType: "json", jsonp: "callBack", jsonpCallBack: `Peanut_Ajax_${Date.now()}_${Math.random() .toString() .replace(".", "")}`, async: true, success(data: any) { console.log("请求成功:", data); }, }; constructor(agrObj?: AjaxConfig) { for (const key in agrObj) { if (Object.prototype.hasOwnProperty.call(agrObj, key)) { this.requestSetting[key] = agrObj[key]; } } } private request(agrObj?: AjaxConfig) { for (const key in agrObj) { if (Object.prototype.hasOwnProperty.call(agrObj, key)) { this.requestSetting[key] = agrObj[key]; } }
if (!this.requestSetting.url) { throw new Error("没有URL"); return; }
this.requestSetting.dataType === "jsonp" ? this.jsonpRequest() : this.defaultRequest(); }
private requestParamsTransform(obj: object): string { let result: string = ""; for (const key in obj) { result += `${key}=${obj[key]}&`; } return result.slice(0, -1); }
private defaultRequest() { let { url, type, dataType, success, data, async } = this.requestSetting; let sendParams = null;
const xhr: XMLHttpRequest = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = () => { console.log(xhr.readyState, "onreadystatechange"); if (xhr.readyState === 4 && xhr.status === 200) { const res = dataType === "json" ? JSON.parse(xhr.responseText) : xhr.responseText;
success(res); } };
if (type === "get") { const urlParams = encodeURI(this.requestParamsTransform(data)); url += "?" + urlParams; } xhr.open(type, url, async);
if (type === "post") { sendParams = this.requestParamsTransform(data); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencode"); } xhr.send(sendParams); }
private jsonpRequest() { const { jsonp, jsonpCallBack, url, success, data } = this.requestSetting; window[jsonpCallBack] = success; const request: string = this.requestParamsTransform(data);
const scriptNode: HTMLScriptElement = document.createElement("script"); scriptNode.src = `${url}?${jsonp}=${jsonpCallBack}&${request}`;
const head: HTMLHeadElement = document.getElementsByTagName("head")[0]; head.appendChild(scriptNode); } }
|