我有一个Web应用程序,我正在将一些数据检索到bootstrap表中,我现在要做的是使用jQuery DataTable
而不是当前,因为它有太多有用的功能。
目前我正在使用OOP方法从服务器端检索数据,其中类对象表示特定表中的数据行,该对象包含存储列名和值的字典。
我现在正在做的是我正在检索这些类对象并将每个对象的每个字典附加到List<Item>
中,然后使用JavaScriptSerializer
对象序列化此列表,并且此对象返回遵循JSON
格式:
[
{
"slno":"2",
"status_message":"Lights still flashing",
"crm_services_id":"1", "subject_id":"Lights are flashing",
"severity_id":"5",
"user_id":"husain.alhamali",
"status_id":"1"
},
{
"slno":"3",
"status_message":"lights working fine",
"crm_services_id":"2",
"subject_id":"Lights are flashing",
"severity_id":"3",
"user_id":"husain.alhamali",
"status_id":"2"
}
]
当我尝试使用此对象填充我的DataTable AJAX
时,我收到了错误消息:
无效的JSON响应
我看到了JSON
可接受的有效DataTable
响应的一些示例,如下所示:
{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
]
}
现在我的问题是,是否有任何工具或插件可以将我的JSON
字符串重新格式化为可接受的格式,如上所述?
答案 0 :(得分:2)
dataTable需要从具有以下键的ajax响应返回的json数据 数据 画画 3. recordsTotal 4. recordsFiltered
答案 1 :(得分:1)
Use this:
var data = list.Select(u => u.GetType()
.GetProperties()
.Select(p => p.GetValue(u, null)));
example
public class User
{
public int userId { get; set; }
public string name { get; set; }
}
public class Programm
{
static void Main()
{
var list = new List<User>();
list.Add(new User
{
userId = 1,
name = "name 1",
});
list.Add(new User
{
userId = 2,
name = "name 2",
});
var data = list.Select(u => u.GetType()
.GetProperties()
.Select(p => p.GetValue(u, null)));
Console.WriteLine(new JavaScriptSerializer().Serialize(new
{
data = data
}));
}
}
result
{
"data" : [
["1", "name 1"],
["2", "name 2"]
]
}
答案 2 :(得分:1)
使用此HTML:
<table id="example"></table>
这个JS将创建一个表:
var data = [{
"slno": "2",
"status_message": "Lights still flashing",
"crm_services_id": "1",
"subject_id": "Lights are flashing",
"severity_id": "5",
"user_id": "husain.alhamali",
"status_id": "1"
}, {
"slno": "3",
"status_message": "lights working fine",
"crm_services_id": "2",
"subject_id": "Lights are flashing",
"severity_id": "3",
"user_id": "husain.alhamali",
"status_id": "2"
}];
function getColumns(){
for(var i = 0; i < data.length; i++){
let columnsArray = [];
var keys = Object.keys(data[i]);
for(k in Object.keys(data[i])){
if(data[i].hasOwnProperty(keys[k])){
columnsArray.push({
"data":keys[k]
});
}
}
return columnsArray;
}
}
$(document).ready(function() {
var table = $('#example').DataTable({
"columns": getColumns(),
"data": data
});
});
工作example。希望有所帮助。