我的Ajax JavaScript表单提交/显示异常,xhr.send()报错该如何修复?
问题排查与修改方案
核心问题:缺少错误处理逻辑
当前代码仅处理了请求成功(状态码200)的场景,一旦请求失败(比如add.php路径错误、服务器报错、网络异常),没有任何回调处理,导致loading.gif一直显示,无法定位具体问题。
具体修改步骤:
补充请求失败的处理分支
在onreadystatechange回调中,除了处理成功状态,还要覆盖其他状态码的情况,同时在控制台打印错误信息方便排查:xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { var data = xhr.responseText; DisplayAfterLoad(data); var button = document.getElementById("saveForm"); button.addEventListener("click", function(event) { event.preventDefault(); recordAdd(); }); } else { // 请求失败时替换loading为错误提示 div.innerHTML = '<p>加载失败,请稍后重试</p>'; console.error('请求错误,状态码:', xhr.status); console.error('响应内容:', xhr.responseText); } } }添加网络异常监听
部分网络问题(比如断网)不会触发readyState == 4,需要单独监听error事件:xhr.onerror = function() { div.innerHTML = '<p>网络异常,请检查网络连接</p>'; console.error('网络请求失败'); }验证请求地址正确性
确认add.php的路径是否正确:- 如果和当前页面同目录,路径没问题;
- 如果在子目录(比如
api/add.php),需要修正路径; - 可以直接在浏览器地址栏输入
add.php的完整URL,确认是否能正常返回表单内容。
避免重复绑定事件(可选优化)
多次调用DisplayForm()会给saveForm按钮重复绑定点击事件,导致recordAdd()执行多次,建议提前移除旧事件再绑定:// 单独定义回调函数 function handleSaveClick(event) { event.preventDefault(); recordAdd(); } // 绑定前先移除旧事件 var button = document.getElementById("saveForm"); button.removeEventListener("click", handleSaveClick); button.addEventListener("click", handleSaveClick);
修改后的完整代码:
function DisplayForm() { var div = document.getElementById("formDiv"); div.classList.toggle("show"); div.innerHTML = '<img class="loadingImg" src="images/loading.gif" alt="Loading..." height="60" width="60" border="0">'; var xhr = new XMLHttpRequest(); xhr.open('GET', "add.php", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { var data = xhr.responseText; DisplayAfterLoad(data); var button = document.getElementById("saveForm"); button.removeEventListener("click", handleSaveClick); button.addEventListener("click", handleSaveClick); } else { div.innerHTML = '<p>加载失败,请稍后重试</p>'; console.error('请求错误,状态码:', xhr.status); console.error('响应内容:', xhr.responseText); } } }; xhr.onerror = function() { div.innerHTML = '<p>网络异常,请检查网络连接</p>'; console.error('网络请求失败'); }; xhr.send(); } function handleSaveClick(event) { event.preventDefault(); recordAdd(); }
内容的提问来源于stack exchange,提问作者Mr_Thomas
相关产品推荐
相关产品推荐

