javascript - 如何将数据从控制器传递到javascript?
问题描述
在我的index
页面上,我有用于重定向到教师页面的按钮。
index.html
:
在这里,我有按钮<button id="getAllTeachers" type="button" class="btn btn-primary">Teachers</button>
,并且这里有一个脚本:
<script>
document.querySelector('#getAllTeachers')
.addEventListener('click',() => {
window.location.href = "/teacherController/check"
});
</script>
当我单击上面的按钮时,当然,它会重定向到我的TeacherController
类,在下面我附加了来自控制器的代码以及我尝试将参数传递给 html 页面:
RestController
@RequestMapping("/teacherController")
public class TeacherController {
private static final String TEACHER_MODEL = "teacher";
@Autowired
TeacherService teacherService;
@RequestMapping("check")
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject(teacherService.getAll());
modelAndView.setViewName("/teacherViews/teachersPage");
return modelAndView;
}
teacherViews/teachersPage
:
<script src="/getTeachers.js"></script>
<div class="container">
<table class="teacherTable" border="1" width="100%" cellpadding="5">
<thead>
<th>TEACHER ID</th>
<th>TEACHER NAME</th>
<th>TEACHER POSITION</th>
<tbody id="teacherBody">
</tbody>
</table>
并且getTeachers.js
:
GET: $(document).ready(
function () {
// GET REQUEST
$("#getAllTeachers").click(function (event) {
event.preventDefault();
ajaxGet();
});
// DO GET
function ajaxGet() {
$.ajax({
type: "GET",
url: "teacherController/check",
success: function (result) {
if (result.status == "success") {
var custList = "";
$.each(result.data,
function (i, teacher) {
var Html = "<tr>" +
"<td>" + teacher.teacherId + "</td>" +
"<td>" + teacher.teacherName + "</td>" +
"<td>" + teacher.position + "</td>" +
"</tr>";
console.log("Teacher checking: ", teacher);
$('#teacherBody').append(Html);
});
console.log("Success: ", result);
} else {
console.log("Fail: ", result);
}
},
error: function (e) {
console.log("ERROR: ", e);
}
});
}
})
我的问题是我需要打印数据库中的所有教师,但它只打印没有数据的表列的名称..
解决方案
Controller
提供检查方法返回的对象标识符是个好主意。(我不明白你想用 Ajax 做什么。)
modelAndView.addObject("teachers", teacherService.getAll());
你给老师看的桌子应该是这样的。
<table>
<thead>
<tr>
<th>Teacher ID</th>
<th>Teacher Name</th>
<th>Teacher Position</th>
</tr>
</thead>
<tbody id="teacherBody">
<tr th:each="teacher : ${teachers}">
<td th:text="${teacher.id}" />
<td th:text="${teacher.name}" />
<td th:text="${teacher.position}" />
</tr>
</tbody>
</table>
推荐阅读
- java - 如何从 Java 应用程序获取 Jenkins 环境变量?
- r - 两个轴承之间的差异(角度)
- c# - C# 从 .txt 扩展名中删除具有更改文件名的行
- python - Tensorflow 中的 CNN 手术:从批量大小 1 到批量大小无
- ruby-on-rails - 跳过 Devise gem 的电子邮件验证会导致唯一性错误
- asterisk - MYSQL() 函数在星号拨号计划中不起作用
- c - 指针 MISRA 违规的算术
- javascript - 可以对外部网页进行ajax调用吗?
- java - 用于用户管理的 Vaadin ThreadLocal
- kubernetes - kube-proxy 如何在主机节点上运行 iptables 命令,同时在进程隔离容器中运行?