如何在HTML表单中使用PATCH方法向服务器发送数据?代码无效求助
问题排查与修复方案
HTML 部分问题
- ID重复冲突:form和input的id都设为
alter,DOM中ID必须唯一,会导致后续获取元素时出现异常。 - 按钮默认行为未阻止:button默认是
submit类型,点击后会触发表单的默认POST提交,页面刷新会中断你的fetch请求。
JS 部分问题
- 元素获取错误:你用
alter_name.value试图获取输入值,但alter_name是当前函数名,并非input元素。需要通过正确的DOM选择器获取输入框。 - Body格式错误:fetch的body要求是JSON字符串,你直接传入了对象,服务器无法解析。需要用
JSON.stringify()转换。 - 语法错误:fetch调用后多了个逗号,正确的链式调用应该是
fetch().then(),而非fetch(),then()。 - 未处理错误:缺少catch块,无法排查请求失败的具体原因。
修正后的代码
HTML
<form class="type-title" method="POST" id="alter-form"> <input type="hidden" name="_method" value="PATCH"/> <input id="alter-input" type="text" name="alter"/> <button type="button" onclick="alter_name();">update</button> </form>
JS
function alter_name(){ const inputEl = document.getElementById('alter-input'); fetch("http://127.0.0.1:3000/api/member", { method: 'PATCH', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ "name": inputEl.value.toString() }) }) .then((response) => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then((data) => { console.log(data); }) .catch((error) => { console.error('请求失败:', error); }) }
内容的提问来源于stack exchange,提问作者Warren Hogan
相关产品推荐
相关产品推荐

