Я создал приложение Springboot, и у меня есть две HTML-страницы: «icecream.html» и «orders.html». Теперь я хочу получить данные из моей таблицы заказов (в postgresql) и показать их в виде страницы orders.html.
Это мой класс контроллера для заказов
@RestController(value = "/icecream")
public class OrderController {
@Autowired
public IcecreamDao icecreamDao;
@GetMapping("/orders")
public List<Icecream> icecreamInformation() {
List<Icecream> icecreams = icecreamDao.getData();
return icecreams;
}
}
Это моя страница orders.html
<!DOCTYPE HTML>
<html xmlns:th = "http://www.thymeleaf.org">
<head>
<link rel = "stylesheet" type = "text/css" href = "css/style.css">
<script type = "text/javascript" src = "js/call.js"> </script>
<script src = "Scripts/jquery-1.9.1.min.js"></ script >
<link href = "Content/bootstrap.min.css" rel = "stylesheet" />
<script src = "Scripts/jquery-1.9.1.min.js"> </ script >
<script src = "Scripts/bootstrap.min.js"> </ script >
<script>
$(document).ready(function () {
productList();
});
</script>
</head>
<body>
<div class = "container">
<div class = "starter-template">
<fieldset>
<h1> <u>Your Order</u> </h1>
<table id = "productTable" border = "1">
<th>Order Number</th>
<th>Order Date</th>
<th>Quantity</th>
<th>Item Name</th>
<th>Price</th>
<th>Total</th>
</table>
</fieldset>
</div>
</div>
</body>
</html>
Это мой файл вызова .js
function productList() {
$.ajax({
url :'/orders',
type : 'GET',
dataType : 'json',
success : function(icecreamList) {
productListSuccess(icecreamList);
},
error : function(request, message, error) {
handleException(request, message, error);
}
});
}
function productListSuccess(icecreamList) {
$.each(icecreamList, function(index, product) {
productAddRow(product);
});
}
function productAddRow(product) {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(productBuildTableRow(product));
}
function productBuildTableRow(product) {
var ret = "<tr>" + "<td>" + product.name + "</td>" + "<td>" +product.price
+ "</td>" + "<td>" + product.qty + "</td>" + "<td>" + product.total
+ "</td>" + "</tr>";
return ret;
}
function handleException(request, message, error) {
var msg = "";
msg += "Code: " + request.status + "\n";
msg += "Text: " + request.statusText + "\n";
if (request.responseJSON != null) {
msg += "Message" + request.responseJSON.Message + "\n";
}
alert(msg);
}
Он успешно предоставляет набор данных из моей БД. Но не давать его как мою html-страницу. Пожалуйста, кто-нибудь объясните мне, что пошло не так...



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Я скопировал ваш HTML и JS в этот фрагмент. Поскольку вы говорите, что ajax успешно возвращается, я включил только счастливый путь js с некоторыми тестовыми данными. единственная проблема, которую я вижу, заключается в том, что у вас нет номера заказа или даты заказа в вашем объекте данных. в результате ваша таблица будет отключена от заголовка. Поскольку эти функции, включенные ниже, работают, я бы рекомендовал использовать ваши инструменты разработчика, чтобы увидеть, есть ли синтаксическая ошибка, которая взрывает ваш js. Я предполагаю, что если вы переместите свой тег script с передней части html на заднюю часть, все начнет щелкать. чтобы подтвердить это, используйте консоль разработчика. вероятно, он выдаст ошибку о том, что ваш HTML-элемент не существует, поскольку js выполняется до завершения загрузки вашего html. безопасное эмпирическое правило всегда вставлять js в конец файла.
function productListSuccess(icecreamList) {
$.each(icecreamList, function(index, product) {
productAddRow(product);
});
}
function productAddRow(product) {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(productBuildTableRow(product));
}
function productBuildTableRow(product) {
var ret = "<tr>" + "<td>" + product.name + "</td>" + "<td>" +product.price
+ "</td>" + "<td>" + product.qty + "</td>" + "<td>" + product.total
+ "</td>" + "</tr>";
return ret;
}
productListSuccess([
{
name: 'Test 1',
price: 1,
qty: 1,
total: 1
},
{
name: 'Test 2',
price: 2,
qty: 2,
total: 4
}
]);<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class = "container">
<div class = "starter-template">
<fieldset>
<h1> <u>Your Order</u> </h1>
<table id = "productTable" border = "1">
<th>Order Number</th>
<th>Order Date</th>
<th>Quantity</th>
<th>Item Name</th>
<th>Price</th>
<th>Total</th>
</table>
</fieldset>
</div>
</div>
</body>
мой ответ ниже решил вашу проблему? пожалуйста, обновите свой вопрос, указав более подробную информацию, или отметьте ответ, если он был полезен. Спасибо.