如何将Spring Boot Controller数据传递到Bootstrap Modal并局部更新
实现方案
方案1:返回JSON直接填充字段(性能最优,推荐)
1. 调整Controller返回JSON结构
给接口加上@ResponseBody注解,直接返回学生信息键值对,不需要渲染页面片段:
@RequestMapping(value = "/searchstudent", method=RequestMethod.POST) @ResponseBody public Map<String, Object> searchStudent(@ModelAttribute(value="foo") Foo foo) { // 此处替换为实际数据库查询逻辑 Map<String, Object> studentInfo = new HashMap<>(); studentInfo.put("name", "查询到的学生姓名"); studentInfo.put("classs", "查询到的学生班级"); // 其他需要返回的字段依次放入即可 return studentInfo; }
2. 给Modal内待填充元素加唯一ID
修改HTML代码,给需要更新的元素增加id属性,方便JS定位:
<!-- 原代码保留,仅新增id属性 --> <h4 id="stu-name" class="card-title"></h4> <h6 id="stu-class" th:text="${classs}" class="card-category text-gray"></h6> <h2 id="stu-other" class="card-category text-orange" style="font-weight: bold;text-decoration: underline;"></h2>
3. 监听自动补全选中事件发送AJAX请求
在自动补全组件的选中回调中发起异步请求,拿到返回值后直接填充到对应字段,无需刷新Modal:
// 以jQuery UI Autocomplete为例,其他自动补全组件的选中回调逻辑一致 $("#autocomplete-ajax").autocomplete({ // 你原有自动补全的数据源配置保留不变 source: yourAutoCompleteSourceConfig, select: function(event, ui) { // 选中选项后发起异步请求 $.post("/searchstudent", {bar: ui.item.value}, function(res) { // 直接填充字段 $("#stu-name").text(res.name); $("#stu-class").text(res.classs); // 其他字段依次填充即可 }); return false; } })
方案2:沿用现有返回Thymeleaf片段的逻辑
如果不想修改现有Controller的返回逻辑,可直接异步请求接口拿到渲染后的片段,替换整个Modal内容:
$("#autocomplete-ajax").autocomplete({ source: yourAutoCompleteSourceConfig, select: function(event, ui) { $.post("/searchstudent", {bar: ui.item.value}, function(htmlStr) { // 用返回的渲染后片段替换当前页面的Modal节点 $("#popup1").replaceWith(htmlStr); // 重新初始化自动补全组件(因为原有DOM被替换) initYourAutoComplete(); }); return false; } })
内容的提问来源于stack exchange,提问作者Mcee
相关产品推荐
相关产品推荐

