我正在尝试将DataTables框架添加到此现有示例项目中。该项目包含一个html文件和Javascript文件作为前端,一个java servlet作为后端与MySQL数据库对话。 Java文件从数据库中检索信息,并将JSON数组发送到javascript文件以实际填充表。 html文件作为一个骨架(无论如何这是我的理解,请纠正我,如果它是错的请)。目前我可以显示数据表和初始数据,但格式化已关闭,一旦我尝试对表进行排序,数据就会消失。
这是我第一次加载时的样子
我尝试排序或更改条目数
我在html中添加了下面所需的函数调用,就像许多基本示例所示。
$(document).ready( function () {
$('#example').DataTable();
console.log("In ready function");
} );

我认为发生的事情是我尝试排序后无法再次运行javascript文件。我已经尝试将调用添加到javascript文件和/或在线跟踪其他示例,但没有任何工作。我是javascript和JQuery的新手但我觉得这可以通过改变我调用datatables函数的位置和/或方式来解决。任何帮助将不胜感激。我把整个html和javascript文件放在下面。如前所述,Java文件只是将JSON数组发送到Js文件。
<!-- This example is following frontend and backend separation.
This .html performs two steps:
1. Create a html template skeleton, with all the elements defined (some left empty) and named with ids.
2. Load index.js to populate the data into empty elements.
-->
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" type="text/css"
href="https://cdn.datatables.net/v/bs4-4.0.0/jq-3.2.1/dt-1.10.16/datatables.min.css" />
<script type="text/javascript"
src="https://cdn.datatables.net/v/bs4-4.0.0/jq-3.2.1/dt-1.10.16/datatables.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
$('#example').DataTable();
console.log("In ready function");
} );
</script>
<title>Star List</title>
</head>
<body>
<h1>stars</h1>
<!-- Id "star_table" is useful for jQuery to find the html element with id, class here is mapping to Bootstrap defined class CSS -->
<table id=star_table class="display">
<!-- Create a table header -->
<thead>
<tr>
<!-- Titles of each column-->
<th>Name</th>
<th>Birth Year</th>
</tr>
</thead>
<!-- Table body is left empty here, will be populated with the data retrieved with index.js -->
<!-- Again, id "star_table_body" is useful for jQuery to find this html element -->
<tbody id=star_table_body></tbody>
</table>
<!-- Load jQuery and Bootstrap JS -->
<!-- Load our own JS file -->
<!-- The path is relative to index.html, since these two files are in the same directory -->
<!-- Note the url does not contain a "/" in the beginning, which means the url is relative to current path
otherwise the url is relative to the root path-->
<script src="index.js"></script>
</body>
</html>
&#13;
/**
* This example is following frontend and backend separation.
*
* Before this .js is loaded, the html skeleton is created.
*
* This .js performs two steps:
* 1. Use jQuery to talk to backend API to get the json data.
* 2. Populate the data to correct html elements.
*/
/**
* Handles the data returned by the API, read the jsonObject and populate data into html elements
* @param resultData jsonObject
*/
function handleStarResult(resultData) {
console.log("handleStarResult: populating star table from resultData");
$('#star_table').DataTable();
// Populate the star table
// Find the empty table body by id "star_table_body"
let starTableBodyElement = jQuery("#star_table_body");
// Iterate through resultData, no more than 10 entries
for (let i = 0; i < Math.min(10, resultData.length); i++) {
// Concatenate the html tags with resultData jsonObject
let rowHTML = "";
rowHTML += "<tr>";
rowHTML +=
"<th>" +
// Add a link to single-star.html with id passed with GET url parameter
'<a href="single-star.html?id=' + resultData[i]['star_id'] + '">'
+ resultData[i]["star_name"] + // display star_name for the link text
'</a>' +
"</th>";
rowHTML += "<th>" + resultData[i]["star_dob"] + "</th>";
rowHTML += "</tr>";
// Append the row created to the table body, which will refresh the page
starTableBodyElement.append(rowHTML);
}
}
/**
* Once this .js is loaded, following scripts will be executed by the browser
*/
// Makes the HTTP GET request and registers on success callback function handleStarResult
jQuery.ajax({
dataType: "json", // Setting return data type
method: "GET", // Setting request method
url: "api/stars", // Setting request url, which is mapped by StarsServlet in Stars.java
success: (resultData) => handleStarResult(resultData) // Setting callback function to handle data returned successfully by the StarsServlet
});
&#13;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import javax.annotation.Resource;
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 javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
// Declaring a WebServlet called StarsServlet, which maps to url "/api/stars"
@WebServlet(name = "StarsServlet", urlPatterns = "/api/stars")
public class StarsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Create a dataSource which registered in web.xml
@Resource(name = "jdbc/moviedb")
private DataSource dataSource;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json"); // Response mime type
// Output stream to STDOUT
PrintWriter out = response.getWriter();
try {
// Get a connection from dataSource
Connection dbcon = dataSource.getConnection();
// Declare our statement
Statement statement = dbcon.createStatement();
String query = "SELECT * from stars";
// Perform the query
ResultSet rs = statement.executeQuery(query);
JsonArray jsonArray = new JsonArray();
// Iterate through each row of rs
while (rs.next()) {
String star_id = rs.getString("id");
String star_name = rs.getString("name");
String star_dob = rs.getString("birthYear");
// Create a JsonObject based on the data we retrieve from rs
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("star_id", star_id);
jsonObject.addProperty("star_name", star_name);
jsonObject.addProperty("star_dob", star_dob);
jsonArray.add(jsonObject);
}
// write JSON string to output
out.write(jsonArray.toString());
// set response status to 200 (OK)
response.setStatus(200);
rs.close();
statement.close();
dbcon.close();
} catch (Exception e) {
// write error message JSON object to output
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("errorMessage", e.getMessage());
out.write(jsonObject.toString());
// set reponse status to 500 (Internal Server Error)
response.setStatus(500);
}
out.close();
}
}