使用POST方法向Java后端发送JSON数据时遇阻求助
前端POST JSON到Java后端无数据接收问题
我正在开发表单前端,尝试通过POST方法向Java后端发送JSON数据,但后端接收不到任何数据。我认为问题出在前端脚本而非网络连接,相关代码如下:
相关代码
script.js
const signUpBtnForm = document.querySelector('.form__btn_signup') signUpBtnForm.addEventListener('click', function () { let xhr = new XMLHttpRequest(); let json = JSON.stringify({ name: document.reg.name, phone: document.reg.phone, password: document.reg.password }); xhr.open("POST", "http://localhost:8080/users"); xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8'); xhr.send(json); xhr.onload = () => alert(xhr.response); })
index.html
<!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>Форма авторизации</title> <link rel="stylesheet" href="style.css"> <script src="script.js" defer></script> </head> <body> <article class="container"> <form action="#" name="reg" class="form form_signup" method="post"> <h3 class="form__title"> Регистрация </h3> <p> <input type="text" name="name" class="form__input" placeholder="ФИО"> </p> <p> <input type="text" name="phone" class="form__input" placeholder="Телефон"> </p> <p> <input type="password" name="password" class="form__input" id="password_registration" placeholder="Пароль"> </p> <p class="password-length">Пароль слишком короткий</p> <p class="password-includes">В пароли есть недопустимые символы: .@$!%*#?&><)(^-_</p> <p> <input type="password" class="form__input" id="second_password_registration" placeholder="Подтвердите пороль"> </p> <p class="check-similar">Пароли не совпадают</p> <p> <button class="form__btn form__btn_signup">Зарегистрироваться</button> </p> </form> </article> </body> </html>
问题诊断与修复方案
1. 阻止表单默认提交行为
按钮属于表单内元素,点击会触发表单默认提交(页面跳转),导致XHR请求被中断。必须在事件处理函数中添加阻止默认行为的代码:
signUpBtnForm.addEventListener('click', function (event) { event.preventDefault(); // 关键:阻止表单跳转 // 后续XHR代码... })
2. 正确获取输入框的值
你当前直接传递DOM元素对象(document.reg.name)而非输入框的实际值,JSON序列化后会生成无效结构,后端无法解析。需要改为获取.value属性:
let json = JSON.stringify({ name: document.reg.name.value, phone: document.reg.phone.value, password: document.reg.password.value });
3. 增加请求调试(可选)
添加错误监听和状态日志,方便排查请求异常:
xhr.onerror = () => console.error('请求发送失败'); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { console.log('响应状态码:', xhr.status); console.log('响应内容:', xhr.response); } };
4. 前置输入验证(可选)
发送请求前检查必填字段是否为空,避免无效请求:
const name = document.reg.name.value.trim(); const phone = document.reg.phone.value.trim(); const password = document.reg.password.value.trim(); if (!name || !phone || !password) { alert('请填写所有必填字段'); return; }
内容的提问来源于stack exchange,提问作者MaxuwkaPlus
相关产品推荐
相关产品推荐

