回车按钮触发错误页面/重复消息,移除事件仍生效问题求助
问题分析与解决方案
问题描述
点击回车按钮时,页面要么显示“Bad Request Did not attempt to load JSON data because the request Content-Type was not 'application/json'”错误,要么偶尔自动重复生成聊天内容并添加到div中。已移除回车按键事件,但回车功能仍生效,推测可能与Bootstrap有关。
核心问题与解决办法
1. 回车触发表单默认提交(导致Bad Request错误)
- 原因:输入框嵌套在
<form>标签内,按回车会触发HTML表单的默认提交行为——浏览器会以application/x-www-form-urlencoded格式提交表单,而非你通过fetch发送的JSON格式,这直接引发了后端的Content-Type校验错误。该问题和Bootstrap无关,是HTML原生特性导致的。 - 解决:
- 方法一:给表单添加
onsubmit="return false;",直接阻止默认提交行为:<form method="post" onsubmit="return false;"> - 方法二:给输入框绑定回车事件,手动拦截默认行为并触发自定义逻辑:
const input = document.getElementById("textinput"); input.addEventListener('keydown', function(e) { if (e.key === 'Enter') { e.preventDefault(); // 阻止表单默认提交 insertText(); // 执行你的提交逻辑 } });
- 方法一:给表单添加
2. 聊天内容重复生成
- 原因:
- 表单默认提交和自定义
insertText逻辑被同时触发,导致多次调用API并添加内容; - 两个
fetch请求是异步并行执行的,时序混乱可能导致重复获取数据;
- 表单默认提交和自定义
- 解决:
- 确保仅触发一次
insertText逻辑(通过上述阻止表单默认提交实现); - 将获取回复的请求嵌套在POST请求的回调中,保证先完成数据提交再获取回复:
fetch('/dashboard', { method: 'POST', body: JSON.stringify({ user_text: json_entry }), headers: { 'Content-Type': 'application/json' } }) .then(response => { if (!response.ok) throw new Error('提交失败'); return fetch('/dashboard/api'); // POST完成后再请求回复 }) .then(response => response.json()) .then(data => { let div = document.createElement('div'); let robot_reply = document.createTextNode(data); div.appendChild(robot_reply); document.getElementById("hello").appendChild(div); document.getElementById('textinput').value = ''; // 提交后清空输入框 }) .catch(err => console.error('请求出错:', err));
- 确保仅触发一次
3. HTML结构修复
你的代码中存在标签未闭合问题(<div class="input-group-append">和<button>未闭合),可能导致浏览器解析异常,引发奇怪行为。修复后的表单结构如下:
<form method="post" onsubmit="return false;"> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Type here...." aria-label="Recipient's username" aria-describedby="basic-addon2" name="userid" id="textinput"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button" value="hello world" id="button">Submit</button> </div> </div> </form>
内容的提问来源于stack exchange,提问作者Luis Pereira
相关产品推荐
相关产品推荐

