如何在XMLHttpRequest中使用beforeSend实现按钮文本与状态修改
实现点击按钮时修改文本并禁用(基于XMLHttpRequest)
首先明确:原生XMLHttpRequest并没有内置的beforeSend方法(这个是jQuery Ajax的特性),但我们可以在发送请求前后手动处理按钮状态,效果和beforeSend完全一致。
按照你的需求,修改代码的核心思路是:
- 点击按钮后立即修改按钮文本并设置为禁用(这就相当于模拟
beforeSend的触发时机) - 请求完成后(不管成功还是失败),根据场景恢复按钮状态(比如请求失败时让用户可以重试)
下面是修改后的完整代码:
const form = document.querySelector(".request form"), continueBtn = form.querySelector(".button input"), errorText = form.querySelector(".error-text"), successText = form.querySelector(".success-text"); form.onsubmit = (e) => { e.preventDefault(); // 阻止表单默认提交行为 }; continueBtn.onclick = () => { // 模拟beforeSend:修改按钮状态和文本 const originalText = continueBtn.value; // 保存原始文本,方便后续恢复 continueBtn.value = "提交中..."; // 修改按钮文本 continueBtn.disabled = true; // 禁用按钮,防止重复点击 // 初始化XMLHttpRequest let xhr = new XMLHttpRequest(); xhr.open("POST", "phpControllers/signup.php", true); xhr.onload = () => { if (xhr.readyState === XMLHttpRequest.DONE) { // 请求完成后,根据结果处理按钮状态 if (xhr.status === 200) { let data = xhr.response; if (data === "success") { location.href = "index.php"; // 成功跳转则无需恢复按钮 } else { errorText.innerHTML = data; errorText.style.display = "block"; successText.style.display = "none"; // 失败时恢复按钮,允许用户重试 continueBtn.value = originalText; continueBtn.disabled = false; } } else { // 请求状态码异常时恢复按钮 errorText.innerHTML = "请求失败,请稍后重试"; errorText.style.display = "block"; successText.style.display = "none"; continueBtn.value = originalText; continueBtn.disabled = false; } } }; // 处理网络错误场景 xhr.onerror = () => { errorText.innerHTML = "网络异常,请检查连接"; errorText.style.display = "block"; successText.style.display = "none"; // 恢复按钮状态 continueBtn.value = originalText; continueBtn.disabled = false; }; // 发送表单数据 let formData = new FormData(form); xhr.send(formData); };
关键细节说明:
- 点击按钮后立即修改状态,是最贴合
beforeSend逻辑的处理时机,能有效防止用户重复提交 - 保存按钮原始文本,确保请求失败后可以恢复到初始状态
- 覆盖了所有异常场景(请求状态码错误、网络故障)的按钮恢复逻辑,避免出现用户无法操作的情况
内容的提问来源于stack exchange,提问作者Mdesign
相关产品推荐
相关产品推荐

