点击提交按钮时AJAX请求被取消,页面刷新问题求助
解决提交按钮导致页面刷新、AJAX请求被取消的问题
核心问题与修复步骤:
- 未阻止表单默认提交行为:你的代码仅判断了
event.preventDefault方法是否存在,但从未调用它。点击提交按钮会触发表单默认的提交刷新行为,这直接导致AJAX请求被中断取消。必须调用event.preventDefault()来阻止页面刷新。 - JSON序列化错误:
JSON.stringify(firstName, lastName, emailAddress)的写法错误。该函数第一个参数应为需要序列化的对象,你需要把三个表单字段包装成一个对象传入,否则只会序列化firstName,后两个参数无法被正确处理。 - 建议添加AJAX回调:增加
success和error回调函数,便于查看请求状态和排查潜在问题。
修正后的代码:
let URL = "https://6327494d5731f3db9956d362.mockapi.io/users"; $("#submitButton").on("click", (event) => { // 阻止表单默认提交行为,避免页面刷新 event.preventDefault(); let firstName = $("#firstName").val(); let lastName = $("#lastName").val(); let emailAddress = $("#emailAddress").val(); console.log(firstName, lastName, emailAddress); $.ajax({ url: URL, // 将表单字段包装成对象后序列化 data: JSON.stringify({ firstName, lastName, emailAddress }), dataType: "json", type: "POST", contentType: "application/json", crossDomain: true, // 成功回调:查看返回结果 success: function(response) { console.log("提交成功", response); }, // 错误回调:排查请求问题 error: function(xhr, status, error) { console.error("提交失败", status, error); } }); });
额外提醒:如果你的提交按钮嵌套在<form>标签内,阻止默认提交行为是必须的,否则表单会优先执行默认刷新逻辑,打断AJAX请求。
内容的提问来源于stack exchange,提问作者Obsidian Asphodel
相关产品推荐
相关产品推荐

