我正在使用 jsp 创建简单的 CRUD 系统。通过 json 格式传递的数据我通过控制台进行了测试,它传递良好,但数据未显示在数据表上。我不知道为什么。我写了到目前为止我尝试过的内容。
表格
<table id="tbl-projects" class="table table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
jQuery
<script>
get_all()
function get_all()
{
$('#tbl-projects').dataTable().fnDestroy();
$('#etbl-projects').DataTable().ajax.reload();
$.ajax({
url : "all_project.jsp",
type : "GET",
dataType : "JSON",
success:function(data)
{
alert(data.course);
$('#tbl-projects').dataTable({
"aaData": data,
"scrollX": true,
"aoColumns": [
{"sTitle": "StudentName", "mData": "name"},
{"sTitle": "Course", "mData": "course"},
{"sTitle": "Fee", "mData": "fee"},
{
"sTitle": "Edit",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="get_project_details(' + mData + ')">Edit</button>';
}
},
{
"sTitle": "Delete",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-primary" onclick="Remove_details(' + mData + ')">Delete</button>';
}
}
]
});
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
</script>
all_project.jsp Jsp页面
<%@page import="org.json.simple.JSONObject"%>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
String query="select * from records";
Statement stmt=con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
String id =rs.getString("id");
String name =rs.getString("name");
String course =rs.getString("course");
String fee =rs.getString("fee");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("course", course);
json.put("fee", fee);
json.put("id", id);
out.print(json);
out.flush();
}
%>
我已经通过控制台结果进行了测试。屏幕截图如下
{"fee":"10000","name":"john","course":"java","id":"1"}{"fee":"7000","name":"Raja","course":"C#","id":"2"}{"fee":"2323","name":"sad","course":"asd","id":"3"}{"fee":"12000","name":"Nishan","course":"Jsp","id":"4"}
我已附上下面的数据表图像
最佳答案
您的 JSON 格式响应无效(对象之间缺少逗号)。
使用org.json.simple.JSONArray
创建对象列表,例如:
<%@page import="org.json.simple.JSONArray"%>
...
JSONArray list = new JSONArray();
while(rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
String course = rs.getString("course");
String fee = rs.getString("fee");
JSONObject obj = new JSONObject();
obj.put("name", name);
obj.put("course", course);
obj.put("fee", fee);
obj.put("id", id);
list.put(obj);
}
out.print(list.toJSONString());
out.flush();
关于java - Json数据如何使用Jsp传入DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57180086/