调用存储过程将数据绑定到jQuery Datatable(v1.10.16)。删除记录时,Ajax调用会成功删除数据库中的记录。在delete的Callback中,我重新绑定了jQuery Datatable,但我刚删除的记录仍然存在。如果我刷新页面,我刚刚删除的记录不再在数据表中。
function DeleteFundingSource(id)
{
function callBack(response) {
if (response.d == 'OK') {
$('#<%=lblMessage.ClientID%>').text("Funding Source Archived Successfully");
if ($('#<%=lblMessage.ClientID%>').hasClass("bg-danger"))
$('#<%=lblMessage.ClientID%>').removeClass("bg-danger");
$('#<%=lblMessage.ClientID%>').addClass("bg-success");
GetFundingSources(); //rebind the grid
}
else {
$('#<%=lblMessage.ClientID%>').text(response.d);
if ($('#<%=lblMessage.ClientID%>').hasClass("bg-success"))
$('#<%=lblMessage.ClientID%>').removeClass("bg-success")
$('#<%=lblMessage.ClientID%>').addClass("bg-danger");
}
}
$.ajax({
type: 'GET',
url: '../services/Inv_WS.asmx/DeleteFundingSource',
data: { ID: JSON.stringify(id) },
dataType: 'json',
contentType: "application/json",
success: function (data) {
callBack(data);
},
error: function () {
$("#loading").hide();
alert('Failed to load data in DataTable!');
}
});
}
function GetFundingSources() {
$.ajax({
type: 'GET',
url: '../services/Inv_WS.asmx/GetFundingSource',
dataType: 'json',
contentType: "application/json",
success: function (data) {
$.each(data, function () {
$.each(this, function (k, v) {
body = "<tr>";
body += "<td><span class='glyphicon glyphicon-pencil' title='Edit'></span></td>";
body += "<td>" + v.Name + "<input id='hidID' type='hidden' value='" + v.ID + "' ></td>";
body += "<td><span class='glyphicon glyphicon-remove' OnClick='DeleteFundingSource(" + v.ID + "); return false;' title='Delete'></span></td>";
body += "</tr>";
$("#tblFund tbody").append(body);
});
});
/*DataTables instantiation.*/
var t= $("#tblFund").DataTable();
t.draw(true);
},
error: function (xhr, ajaxOptions, thrownError) {
$("#loading").hide();
alert('Failed to load data in DataTable!');
}
});
}
我在添加新记录或编辑现有记录时使用相同的方法,这些操作成功执行,数据表也相应地反映了更改。
答案 0 :(得分:0)
<强> SOLUTION:强>
我向DOM添加元素的方法就是问题所在。成功解决了这样的问题:
在我的函数范围之外,我添加了一个新变量:var table;
function GetFundingSources() {
table = $("#tblFund").DataTable();
table.clear();
$.ajax({
type: 'GET',
url: '../services/Inv_WS.asmx/GetFundingSource',
dataType: 'json',
contentType: "application/json",
success: function (data) {
$.each(data, function () {
$.each(this, function (k, v) {
body = "<tr>";
body += "<td><span class='glyphicon glyphicon-pencil' title='Edit'></span></td>";
body += "<td>" + v.Name + "<input id='hidID' type='hidden' value='" + v.ID + "' ></td>";
body += "<td><span class='glyphicon glyphicon-remove' OnClick='DeleteFundingSource(" + v.ID + "); return false;' title='Delete'></span></td>";
body += "</tr>";
table.row.add($(body).get(0)).draw();
});
});
},
error: function () {
$("#loading").hide();
// alert('Failed to load data in DataTable!');
}
});
}
解决方案的关键是这一行:
table.row.add($(body).get(0)).draw();
这种方法不是向DOM添加元素,而是实际向数据表添加行。现在删除功能完美无瑕。