我有html页面,点击按钮,发送ajax请求并在表格中显示用户列表,这很好我已经开发了这部分,但问题是,当我再次点击按钮时,数据被添加在旧数据之后的表格中:
我想用新数据覆盖旧数据。
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<button id="but">click me </button>
<div id="test">
<table class="table table-stripped" id="table" style="border: 1px">
</table>
</div>
<script>
$(document).on("click", "#but", function () { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("testServlet", function (responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var $ul = $("#table") // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
console.log(responseJson);
$.each(responseJson, function (index, item) { // Iterate over the JSON array.
$("<tr>").appendTo($ul)
.append($("<td>").text(item.id).appendTo($ul))// Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
.append($("<td>").text(item.fname).appendTo($ul))
.append($("<td>").text(item.lname).appendTo($ul));
});
});
});
</script>
</body>
</html>
servlet处理ajax请求:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
user u = new user(1, "john", "doe");
user u1 = new user(2, "foo", "foo");
user u2 = new user(3, "bar", "bar");
List<user> list = new ArrayList<>();
list.add(u);
list.add(u1);
list.add(u2);
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
答案 0 :(得分:1)
问题是append
每次向新旧数据添加新数据时都会尝试此解决方案:
<script>
$(document).on("click", "#but", function () { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("testServlet", function (responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var $ul = $("#table") // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
console.log(responseJson);
$('#table').html("");
$.each(responseJson, function (index, item) {
$("<tr>").appendTo($ul)
.append($("<td>").text(item.id).appendTo($ul))// Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
.append($("<td>").text(item.fname).appendTo($ul))
.append($("<td>").text(item.lname).appendTo($ul));
});
});
});
</script>