JS获取可编辑div值组装表单提交时对象属性为空如何解决
问题原因
- 取值时机完全错误:你在页面刚加载的初始化阶段就提前读取了所有可编辑div的
innerHTML存到变量里,此时用户还没有输入任何内容,变量存的就是初始的空字符串。这类普通字符串变量不会跟着div内容的变化自动更新,所以不管用户后来输入了什么,点击按钮时读取的还是初始化时拿到的空值。 - 按钮默认行为未拦截:你用的按钮是
type="submit"类型,点击时会触发表单原生的提交跳转逻辑,轻则打断自定义的fetch请求,重则直接导致页面刷新重置所有输入内容。 - 代码存在语法级错误:
- fetch的第一个
.then()没有传入回调函数,直接写了res.json(),不符合Promise链式调用的语法要求 - 第二个
.then()的回调里引用了未定义的res变量,和形参data不匹配 - 接口地址写错了,
http:localhost:5000缺少协议后的双斜杠,正确格式应为http://localhost:5000
- fetch的第一个
修复方案
核心调整逻辑:初始化阶段只缓存DOM元素引用,不要提前读取内容;所有内容的读取动作放到点击事件的回调里,实时获取用户输入的最新值,同时修正其他语法错误。
修复后的完整JS代码如下:
// 初始化阶段只获取DOM元素,不提前读取内容 const firstNameInput = document.querySelector(".firstName"); const secondNameInput = document.querySelector(".secondName"); const marsNameInput = document.querySelector(".marsName"); const emailInput = document.querySelector(".phoneOrEmail"); const passwordInput = document.querySelector(".password"); const submitBtn = document.querySelector(".allIsWell"); submitBtn.addEventListener("click", (e) => { // 阻止表单默认提交跳转 e.preventDefault(); // 点击时实时读取最新输入内容,纯文本场景用textContent更安全,自动过滤HTML标签 const form = { firstName: firstNameInput.textContent.trim(), secondName: secondNameInput.textContent.trim(), marsName: marsNameInput.textContent.trim(), email: emailInput.textContent.trim(), password: passwordInput.textContent.trim() }; console.log(form); // 修正接口地址和fetch链式调用写法 fetch("http://localhost:5000/api/register", { method: "POST", body: JSON.stringify(form), headers: { "Content-Type": "application/json" }, cache: "no-cache" }) .then(res => res.json()) .then(data => { console.log("Success: ", data); }) .catch(error => { console.log("Error: ", error); }); });
补充说明:如果你的场景需要保留用户输入的富文本格式,可以把
textContent替换为innerHTML,但普通注册表单场景用textContent即可,还能避免恶意输入HTML标签导致的XSS风险。
内容的提问来源于stack exchange,提问作者Mohamed Nasr
相关产品推荐
相关产品推荐

