更新商品时无法跳转回addProduct.html且更新不生效如何排查
问题排查与修复方案
一、提交更新后无法跳转的问题
你现有代码存在以下4个致命错误:
- 事件绑定逻辑完全错误:你在代码里监听了不存在的
id="update"表单的提交事件,同时把update-products表单的提交监听嵌套在了前者的回调里,导致提交事件永远不会被触发,点击提交按钮没有任何反应。 - 无效代码运行报错:代码中
id.value = urlId、product.value = urlProduct、price.value = urlPrice三行里,product、price已经是你之前定义的输入框字符串值,不是DOM元素,运行时会直接抛出类型错误,阻塞后续所有逻辑执行。 - 页面元素缺失:更新页面的HTML里没有id为
category的输入框,你JS里尝试读取和赋值category会返回null,也会触发报错。 - fetch响应判断逻辑错误:你直接用
if(response)判断请求成功,哪怕接口返回4xx/5xx错误也会判定为成功,没有校验接口是否真的完成了数据更新。
修复后的updateProduct.js代码
document.addEventListener("DOMContentLoaded", () => { const urlParams = new URLSearchParams(window.location.search); const idLoaded = urlParams.get("id"); const productLoaded = urlParams.get("product"); const priceLoaded = urlParams.get("price"); const categoryLoaded = urlParams.get("category"); // 给表单元素赋值 document.getElementById("product").value = productLoaded; document.getElementById("price").value = priceLoaded; document.getElementById("category").value = categoryLoaded; // 直接绑定正确的表单提交事件,不要嵌套 document.getElementById("update-products").addEventListener("submit", (event) => { event.preventDefault(); // 读取最新的表单值 const product = document.getElementById("product").value; const price = document.getElementById("price").value; const category = document.getElementById("category").value; const payload = { id: idLoaded, product: product, price: price, category: category }; fetch("http://localhost:5005/products/update", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }) .then((response) => { // 先判断接口请求是否真的成功 if (response.ok) { return response.json(); } throw new Error('更新请求失败'); }) .then((res) => { window.alert("更新成功!") location.href = "/addProduct.html"; }) .catch((err) => { console.error(err) window.alert("更新失败,请重试") }); }); });
修复后的更新页HTML代码
需要补充category输入框:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Opdater varer detaljer</title> <script src="updateProduct.js"></script> </head> <body> <form id="update-products"> Product: <input type="text" name="product" id="product" value=""><br> Price: <input type="text" name="price" id="price" value=""><br> Category: <input type="text" name="category" id="category" value=""><br> <br> <input type="submit" value="更新"> </form> </body> </html>
二、更新后商品无法正常展示的问题
需要排查以下3点:
- 确认你的
/products/update接口已经正确把更新后的数据写入了存储的JSON文件,你可以手动打开JSON文件查看对应id的商品是否已经更新为新值。 - 确认你的
addProduct.js代码在页面加载完成时,会主动调用服务端的商品列表接口拉取最新的全部商品数据,而不是用本地缓存的旧数据。 - 确认
addProduct.js拿到最新商品列表后,正确把数据循环渲染到了id为varer的表格里。
内容的提问来源于stack exchange,提问作者Claudio Truong
相关产品推荐
相关产品推荐

