现在我遇到了一个问题。我想使用ajax通过使用来自sql server数据库的数据来显示数据表。当前状态是我使用ajax调用Handler.ashx来连接sql server并将数据转换为json(使用newtonsoft.json)。在ajax中,所有json数据都已从Handler.ashx中接收并存储在变量" msg"可以在页面上成功显示。我想把这个" msg"进入数据表但始终失败。我尝试了几乎所有在线方法设置数据表,但仍然给出不同的错误。我想在js中创建一个数据表并填写我的json数据。但结果是表中没有数据或没有数据。
以下是代码和json数据。
JS:
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
//contentType: "application/json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
cache: false,
success: function (msg) {
//for (var i in msg) {
// $("#eventGrid").append(msg[i]);
//}
//var jsonStr = JSON.stringify(msg);
document.getElementById("result").innerHTML = msg;
$('#eventtable').dataTable({
//"paging": false,
//"searching": false,
//"retrieve": true,
//"bProcessing": true,
//"data": msg.data,
//"datatype": "JSON",
//"ajax": "HandlerAll.ashx",
//"aaData": JSON.parse(msg),
//"ajax":
//"dataSrc":virtualTable
//"aoColumns": [
// { "mData": "ID" },
// { "mData": "FESTIVAL" },
// { "mData": "SUBURB" },
// { "mData": "POSTCODE" },
// { "mData": "WEBSITE" },
// { "mData": "DESCRIPTION" }
// ]
});
},
error: function (data) {
alert("Server error.");
}
})
});
});
json数据(大小取决于搜索条件,表格列应该具有" ID","节日"等等,但没有" virtualTable" ):
{ "virtualTable": [ { "ID": "1", "FESTIVAL": "Antipodes Festival", "SUBURB": "Lonsdale Street, Melbourne", "POSTCODE": "3000", "WEBSITE": "http://www.antipodesfestival.com.au/", "DESCRIPTION": "The greek precinct in melbourne cbd will transform into a huge, free street festival with the hosting of the antipodes lonsdale street festival which will hold sway from 14 february 2015 to 15 february 2015." }, { "ID": "5", "FESTIVAL": "Boite Singers Festival", "SUBURB": "Victoria", "POSTCODE": "3000", "WEBSITE": "http://boite.com.au/index.php", "DESCRIPTION": "The boite singers festival brings you four days of vocal inspiration and sheer fun on the second weekend of january each year." } ] }
答案 0 :(得分:0)
<强>解强>
使用以下代码初始化表格:
$('#eventtable').dataTable({
data: msg.virtualTable,
columns: [
{ data: "ID" },
{ data: "FESTIVAL" },
{ data: "SUBURB" },
{ data: "POSTCODE" },
{ data: "WEBSITE" },
{ data: "DESCRIPTION" }
]
});
<强>样本强>
请参阅this jsFiddle以获取代码和演示。
答案 1 :(得分:0)
由于你得到一个JSON作为响应,我会尝试将它转换为JSON对象,将virtualTable部分取为JSON中的一组记录并将其转换为数组以将其添加到我的表中。
background: url(images/contact/downarrow.svg) no-repeat 96% #f3f3f3;