[英]How to print data from restcontroller using AJAX?
這是我的index.html
:
<script src="/teachers.js"></script>
<table id="table-content" border='1'>
<tr>
<th>Teacher ID</th>
<th>Teacher Name</th>
<th>Teacher Position</th>
</tr>
</table>
teachers.js
:
var service = 'http://localhost:8081/api/v1';
$(document).ready(function(){
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: service + '/teacher/',
// data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var trHTML = '';
$.each(data, function (i, item) {
trHTML += '<tr><td>' + data.Teacher[i].Name + '</td><td>' + data.Teacher[i].Position + '</td></tr>';
});
$('#table-content').append(trHTML);
},
和TeacherController
:
@RestController
@RequestMapping("/api/v1")
public class TeacherController {
private static final String TEACHER_MODEL = "teacher";
@Autowired
TeacherService teacherService;
@GetMapping("/teacher")
public List<Teacher> fetchAllTeacher() {
return teacherService.getAll();
}
當我得到index.html
時,我只有空表,在頁面上只能查看表列的名稱,沒有數據..
我做錯了什么,也許你可以用另一種方法來解決我的問題?
在此先感謝您的幫助!!!
現在我的瀏覽器有一個問題:
錯誤:
瀏覽器 window 中的最后一個錯誤:
Invalid character found in the request target [/api/v1/teacher/?47;?{}
&_=1610297706796.] The valid characters are defined in RFC 7230 and RFC
3986</p><p><b>Description</b>
The server cannot or will not process the request due to something that is perceived to be a client error ( e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
感謝@andrewjames,我解決了這個問題。
我編輯了我的trHTML
teachers.js
,現在它正在工作:
var service = 'http://localhost:8081/';
$(document).ready(function(){
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: service + 'teachers/',
// data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var trHTML = '';
$.each(data, function (i, teacher) {
trHTML += '<tr><td>' + teacher.teacherId + '</td><td>' + teacher.teacherName + '</td><td>' + teacher.position + '</td></tr>';
});
$('#table-content').append(trHTML);
},
error: function (msg) {
alert(msg.responseText);
}
});
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.