1. Set constant
You can set some constants as needed
// constant export const HTTP_GET = 'GET'; export const CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'; export const CONTENT_TYPE_JSON = 'application/json';
2. Encapsulation tool class
Mainly used for data conversion and URL processing
// Serialize the array into a string in URLEncoded format const serializeURLEncoded = param => {<!-- --> const results = []; for (const [key, value] of Object. entries(param)) {<!-- --> results.push(`${<!-- -->encodeURIComponent(key)}=${<!-- -->encodeURIComponent(value)}`); } return results. join(' & amp;'); }; // Serialize the array into a string in JSON format const serializeJSON = param => {<!-- --> return JSON.stringify(param); }; // Get the parameter string in legal format const addURLData = (url, data) => {<!-- --> if (!data) {<!-- --> return ''; } const mark = url.includes('?') ? ' & amp;' : '?'; return `${<!-- -->mark}${<!-- -->data}`; }; export {<!-- --> serializeURLEncoded, serializeJSON, addURLData };
3. Set default parameters
When the user does not specify an argument, the default argument will be used
// import constant import {<!-- --> HTTP_GET, CONTENT_TYPE_FORM_URLENCODED } from './constants.js'; // set default parameters const DEFAULTS = {<!-- --> // request method method: HTTP_GET, // request header parameters params: null, // request body parameters data: null, // Content-Type type contentType: CONTENT_TYPE_FORM_URLENCODED, // Response-Type type responseType: '', // overtime time timeoutTime: 0, // Whether to carry Cookie withCredentials: false, // method to execute on success success() {<!-- --> }, // The method executed when the status code is abnormal httpCodeError() {<!-- --> }, // method to execute on failure error() {<!-- --> }, // method to execute on termination abort() {<!-- --> }, // method to execute on timeout timeout() {<!-- --> } }; export default DEFAULTS;
4. Design Ajax class
// import constant import {<!-- --> HTTP_GET, CONTENT_TYPE_JSON, CONTENT_TYPE_FORM_URLENCODED } from './constants.js'; // import function import {<!-- --> serializeURLEncoded, serializeJSON, addURLData } from './utils.js'; // import default parameters import DEFAULTS from './defaults.js'; // define the Ajax class class Ajax {<!-- --> // Constructor constructor(url, options) {<!-- --> this.url = url; this.options = Object.assign({<!-- -->}, DEFAULTS, options); this.init(); } // initialization method init() {<!-- --> // Initialize XMLHttpRequest const xhr = new XMLHttpRequest(); this.xhr = xhr; // bind event this. bindEvents(); // configuration request xhr.open(this.options.method, this.url + this.addParam(), true); // Set Response-Type this. setResponseType(); // Set whether to carry cookies across domains this. setCookie(); // set timeout this. setTimeout(); // send request this. sendData(); } // method to bind event bindEvents() {<!-- --> const xhr = this. xhr; const {<!-- --> success, httpCodeError, error, abort, timeout } = this.options; // load event xhr.addEventListener('load', () => {<!-- --> if (this.isReady()) {<!-- --> success(xhr. response, xhr); } else {<!-- --> error(xhr); } }, false); // error event xhr.addEventListener('error', () => {<!-- --> error(xhr); }, false); // abort event xhr.addEventListener('abort', () => {<!-- --> abort(xhr); }, false); // timeout event xhr.addEventListener('timeout', () => {<!-- --> timeout(xhr); }, false) } // Method to determine whether the request received the correct response isReady() {<!-- --> const xhr = this. xhr; return (xhr.status >= 200 & amp; & amp; xhr.status < 300) || xhr.status === 304; } // Method to add parameters to the URL addParam() {<!-- --> const {<!-- --> params } = this.options; if (!params) {<!-- --> return ''; } return addURLData(this.url, serializeURLEncoded(params)); } // Method to set Response-Type setResponseType() {<!-- --> this.xhr.responseType = this.options.responseType; } // Method to set whether to carry cookies across domains setCookie() {<!-- --> if (this. options. withCredentials) {<!-- --> this.xhr.withCredentials = true; } } // How to set the timeout period setTimeout() {<!-- --> const {<!-- --> timeoutTime } = this.options; if (timeoutTime > 0) {<!-- --> this.xhr.timeout = timeoutTime; } } // method to send request sendData() {<!-- --> const xhr = this. xhr; // If there is no need to transfer data, send directly if (!this.isHasData()) {<!-- --> return xhr. send(null); } let resultData = null; const {<!-- --> data } = this.options; // Sort by data type if (this.isFormData()) {<!-- --> resultData = data; } else if (this.isURLEncodedData()) {<!-- --> this.setContentType(CONTENT_TYPE_FORM_URLEncoded); resultData = serializeURLEncoded(data); } else if (this.isJSONData()) {<!-- --> this.setContentType(CONTENT_TYPE_JSON); resultData = serializeJSON(data); } else {<!-- --> this. setContentType(); resultData = data; } xhr.send(resultData); } // Method to determine whether data needs to be transferred isHasData() {<!-- --> const {<!-- --> data, method } = this.options; if (!data) {<!-- --> return false; } if (method.toLowerCase() === HTTP_GET.toLowerCase()) {<!-- --> return false; } return true; } // Method to determine whether the data type is FormData isFormData() {<!-- --> return this.options.data instanceof FormData; } // Method to determine whether the data type is URLEncoded isURLEncodedData() {<!-- --> return this.options.contentType.toLowerCase().includes(CONTENT_TYPE_FORM_URLENCODED); } // Method to determine whether the data type is JSON isJSONData() {<!-- --> return this.options.contentType.toLowerCase().includes(CONTENT_TYPE_JSON); } // Method to set Content-Type setContentType(contentType = this.options.contentType) {<!-- --> if (!contentType) {<!-- --> return; } this.xhr.setRequestHeader('Content-Type', contentType); } // Get the XMLHttpRequest object getXMLHttpRequest() {<!-- --> return this. xhr; } } export default Ajax;