Spring Boot项目中Ajax提交表单后无法获取接口响应问题求助
问题排查与解决方案
现有代码的问题点:
- 未阻止表单默认提交行为:你注释了
event.preventDefault(),点击提交按钮后表单会触发默认的整页刷新,Ajax请求还未执行完成页面就被重载,因此看不到响应也无法正常传递数据。 - 事件绑定对象错误:
submit是属于<form>标签的事件,你错误绑定到了type为submit的按钮元素上,事件监听不生效。 - 请求URL缺少协议前缀:直接填写
localhost:8080/convert/会被浏览器识别为相对路径,需要补全http://前缀才能正确访问后端接口。 - 跨域限制:如果你的前端页面不是从
localhost:8080域下加载(比如本地直接打开HTML文件、前端服务运行在其他端口),会触发浏览器同源策略限制,无法正常接收后端响应。
修复后的前端代码:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>Temparature converter</h1> <!-- 给form添加id用于绑定事件 --> <form id="tempForm"> <label for="temp">Choose Type : </label> <select name="type" id="type"> <option value="kelvin">kelvin</option> <option value="fahrenheit">fahrenheit</option> <option value="celsius">celsius</option> </select> <br><br> <label for="from">From Unit : </label> <select name="fromUnit" id="fromUnit"> <option value="kelvin">kelvin</option> <option value="fahrenheit">fahrenheit</option> <option value="celsius">celsius</option> </select> <br><br> <input id="data" name="data" placeholder="Your data" type="text" /> <input type="submit" id="myForm" value="Submit"> </form> <div class="append-to-me"></div> <script> $(document).ready(function(){ // 将submit事件绑定到form元素上 $('#tempForm').submit(function(event){ // 取消注释,阻止表单默认提交刷新行为 event.preventDefault(); var data = {type: $("#type").val(), fromUnit: $("#fromUnit").val(),data: $("#data").val()}; $.ajax({ type: "GET", // 补全http协议前缀 url: "http://localhost:8080/convert/", data: data, cache: false, success: function(response) { console.log(response); $('div.append-to-me').append('<p>转换结果:'+response+'</p>'); }, // 新增错误回调方便排查问题 error: function(xhr, status, error) { console.error('请求失败:', status, error); } }); }); }); </script> </body> </html>
后端跨域配置(Spring Boot)
如果触发跨域限制,在你的后端接口Controller类上添加@CrossOrigin注解即可:
@RestController @CrossOrigin(origins = "*") // 生产环境建议替换为实际的前端域名,避免安全风险 @RequestMapping("/convert") public class TempConverterController { // 你的原有接口逻辑 }
内容的提问来源于stack exchange,提问作者Bulbul Ahmed
相关产品推荐
相关产品推荐

