前端开发javaScript手写AjaxYuXiang123456789101112131415161718192021222324252627282930313233 /** * 手写一个简单的ajax * * @param {string} method - 请求方法 * @param {string} url - 请求地址 * @param {string} data - 请求参数 * @param {function} onSuccessCallback - 请求成功的毁掉 * @param {function} onErrorCallback - 失败的毁掉 */function sendAjaxRequest(method, url, data, onSuccessCallback, onErrorCallback) { let xhr = new XMLHttpRequest(); xhr.open(method, url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { try { const res = JSON.parse(xhr.responseText); onSuccessCallback(res); } catch (error) { onErrorCallback(error); } } else { onErrorCallback(`Error:${xhr.status}`); } } }; if (method === "POST" && data) { xhr.send(JSON.stringify(data)); } else { xhr.send(); }}