我尝试使用HTML显示数据表。它对我有用。我能够获得准确的数据表。
下面是我的HTML和Jquery:
<div class="col-md-9">
<table class="table dt-responsive" id="ItemTable">
<thead>
<tr>
<th> Column1 </th>
<th> Column2</th>
<th>Column3</th>
<th> Column4 </th>
</tr>
</thead>
<tbody>
<tr>
<td>Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
<td>Value 4</td>
</tr>
<tr>
<td>Value 5</td>
<td> Value 6 </td>
<td>Value 7</td>
<td>Value 8</td>
</tbody>
</table>
</div>
我的Jquery:
<script>
$('#ItemTable').DataTable({
responsive: true,
scrollX: true,
lengthMenu: [10, 20, 50, 200, 400]
});
</script>
但是我需要使用我的ajax响应来填充数据表。当我使用下面的代码时,我只能获得简单的html表。但不是数据表。
这是我的Jquery:
<script type="text/javascript">
$("#submit").click(function () {
var Details = JSON.stringify({
SelectedReportName: $("#SelectedReport").val(),
});
$('#target').html('sending..');
var thisURL = '@Url.Action("GetReport", "DQR")';
$.ajax({
url: thisURL,
type: "POST",
dataType: "json",
contentType: "application/json",
data: Details,
success: function (data) {
var table = "";
var iteration = data.HeaderList.length;
var noOfRows = data.ValuesList.length;
var startTag = "<table class='table dt-responsive' id='ItemTable'><thead><tr>";
table = table + startTag;
for (var i = 0; i < iteration; i++) {
var td = ("<th>" + data.HeaderList[i].ColumnHeader + "</th>");
table = table + td;
}
var headEndTag = "</tr></thead>";
table = table + headEndTag;
var bodyStartTag = "<tbody>";
table = table + bodyStartTag;
for (var i = 0; i < noOfRows; i++) {
var tableRow = "<tr>";
table = table + tableRow;
if (data.ValuesList[i].Column1 != null) {
var td = ("<td>" + data.ValuesList[i].Column1 + "</td>");
}
table = table + td;
if (data.ValuesList[i].Column2 != null) {
var td1 = ("<td>" + data.ValuesList[i].Column2 + "</td>");
}
table = table + td1;
var tableEndRow = "</tr>";
table = table + tableEndRow;
}
var endTag = "</tbody></table>";
table = table + endTag;
$("#TableContent").html(table);
}
});
});
</script>
我的HTML:
<div id="TableContent">
//Here I will populate the datatable
</div>
有人可以帮我找出它出错的地方吗?
谢谢!
答案 0 :(得分:1)
您不需要在JS中构建表。您只需要在html中创建一个空表并在JS中启动该表。 DataTable将为您填充数据。
HTML中的:
<table id="your-data-table">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<tr>
</thead>
</table>
在Javascript中:
$("#your-data-table").DataTable({
serverSide: true,
processing: true,
ajax: {
url: thisURL,
type: "POST",
dataType: "json",
contentType: "application/json",
data: Details,
async: true
},
// your other settings
)