[英]How to pass data from controller to 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
class 和下面我附加了 controller 的代码和我尝试将参数传递到 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
检查方法返回的 object 标识符。 (我不明白你想用 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.