Форум по Javascript
Anonymous
Как использовать JavaScript в файле JSP
Сообщение
Anonymous » 14 мар 2025, 18:01
Я сталкиваюсь с проблемой с моим веб -проектом Java с использованием Maven. Я хочу использовать AJAX для получения данных без перезагрузки страницы, но у меня возникают проблемы с отображением ответа в HTML. Вот как я его реализовал:
java servlet
Код: Выделить всё
package com.mycompany.stock_managment.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.mycompany.stock_managment.model.Vente;
import com.mycompany.stock_managment.service.ProductService;
@WebServlet("/searchSellHistory")
public class SearchSellHistoryServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("query");
ProductService productService = new ProductService();
// Get the results based on the search query
List results = productService.searchVentes(query);
// Convert to JSON with Gson
Gson gson = new Gson();
String json = gson.toJson(results);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
< /code>
jsp /js /html < /strong> < /p>
$(document).ready(function() {
$("#searchInput").on("keyup", function() {
let query = $(this).val();
$.ajax({
url: "/stock_managment/searchSellHistory",
type: "GET",
data: { query: query },
dataType: "json",
success: function(response) {
let tableBody = $("#sellHistoryTable tbody");
tableBody.empty(); // Vider le tableau avant d'ajouter les nouveaux résultats
if (typeof response === "string") {
response = JSON.parse(response);
}
console.log("Données reçues après conversion :", response);
response.forEach(function(vente) {
let debtClass = vente.reste_a_payer > 0 ? "text-red-500" : "text-green-500";
console.log(vente);
let row = `
${vente.product_name || 'N/A'}
${vente.quantite || '0'}
${vente.prix || '0'}
${vente.montant_total || '0'}
${vente.paiement || '0'}
0 ? 'text-red-500' : 'text-green-500'}">
${vente.reste_a_payer || '0'}
`;
console.log(row);
tableBody.append(row);
});
}
});
});
});
< /code>
Результат: < /p>
console.log Данные хороши в JSON, но если я попытаюсь составить карту этой таблицы cody.append (row); Каждая строка получает false .
Подробнее здесь:
https://stackoverflow.com/questions/795 ... e-jsp-file
1741964481
Anonymous
Я сталкиваюсь с проблемой с моим веб -проектом Java с использованием Maven. Я хочу использовать AJAX для получения данных без перезагрузки страницы, но у меня возникают проблемы с отображением ответа в HTML. Вот как я его реализовал: [b] java servlet [/b] [code]package com.mycompany.stock_managment.controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.mycompany.stock_managment.model.Vente; import com.mycompany.stock_managment.service.ProductService; @WebServlet("/searchSellHistory") public class SearchSellHistoryServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String query = request.getParameter("query"); ProductService productService = new ProductService(); // Get the results based on the search query List results = productService.searchVentes(query); // Convert to JSON with Gson Gson gson = new Gson(); String json = gson.toJson(results); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } } < /code> jsp /js /html < /strong> < /p> $(document).ready(function() { $("#searchInput").on("keyup", function() { let query = $(this).val(); $.ajax({ url: "/stock_managment/searchSellHistory", type: "GET", data: { query: query }, dataType: "json", success: function(response) { let tableBody = $("#sellHistoryTable tbody"); tableBody.empty(); // Vider le tableau avant d'ajouter les nouveaux résultats if (typeof response === "string") { response = JSON.parse(response); } console.log("Données reçues après conversion :", response); response.forEach(function(vente) { let debtClass = vente.reste_a_payer > 0 ? "text-red-500" : "text-green-500"; console.log(vente); let row = ` ${vente.product_name || 'N/A'} ${vente.quantite || '0'} ${vente.prix || '0'} ${vente.montant_total || '0'} ${vente.paiement || '0'} 0 ? 'text-red-500' : 'text-green-500'}"> ${vente.reste_a_payer || '0'} `; console.log(row); tableBody.append(row); }); } }); }); }); < /code> Результат: < /p> console.log[/code] Данные хороши в JSON, но если я попытаюсь составить карту этой таблицы cody.append (row); Каждая строка получает false . Подробнее здесь: [url]https://stackoverflow.com/questions/79509423/how-to-use-javascript-in-the-jsp-file[/url]