【发布时间】:2020-04-10 22:33:48
【问题描述】:
我是 AJAX 和 API 的新手:
我创建了 API(返回状态项数组)
1- Index.php 的数据表代码如下:
<table id="example1" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th class="center">Edit</th>
<th class="center">Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot class="table-condensed table-bordered">
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
</table>
第二个file2.php包括Javascript和Jquery和Ajax代码:
我编写下面的代码从 api 获取 Json 并将行提取到上表中:
var table = $("#example1 tbody");
$.ajax({
url: 'API_ReadAllSeed_Status.php',
method: "GET",
xhrFields: {
withCredentials: true
},
success: function (data) {
table.empty();
$.each(data.AllStatus, function () {
var Active_Status = "";
//the code below is to set a specific element depending on the result
if (this["STATUS_ACTIVE"] == 1)
{Active_Status = "<td><span class='label label-success'>Activated</span></td>";}
else
{Active_Status = "<td><span class='label label-danger'>Deactivated</span></td>"}
table.append("<tr><td>" + this["STATUS_CODE"] + "</td><td>" + this["STATUS_DESCRIPTION"] + "</td>" + Active_Status + "</td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='fa fa-edit'></i> Edit </a></td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='glyphicon glyphicon-trash'> </i> Delete</a></td> </tr>");
});
}
});
结果: Json fetch 如我所愿成功,但如图所示,行没有插入数据表的主体行中,因为内部没有任何工作。
我的问题:
我如何能够将 Json 数据加载到数据表中并使用其所有功能 [搜索和分页以及每页的行数]。
【问题讨论】:
-
看起来您正在使用一些特殊的表/框架/lib 来生成表。是这样吗?你用的是什么库?
-
@Dekel 看起来像引导程序。在您的 ajax 选项中添加 dataType: 'json' 这会将 json 字符串转换为 javascript 可用的 json 对象/数组。并确保服务器返回一个 json 字符串。还要 DEBUG 将您创建的 html 添加到变量并 console.log 它以查看您的循环正在创建什么
-
是的,它是一个引导数据表,我添加了数据类型:'Json' 并对其进行了调试,结果是带有数组的 Json。但这不会解决我的问题。因为我已经能够获取 Json 数组并使用 .each() 函数获取它,但是在数据表中应用行无法正常使用分页和每页行数和搜索字段。请注意:如果我添加了
手动分页和搜索字段正常工作