javascript - 将 JSON 反序列化为 JavaScript 对象(数据表)
问题描述
我可以从服务器获取数据作为控制台浏览器可以显示的 JSON 表单:
function search() {
// Get the user's input from the page keep to localStorage
localStorage.setItem("searchBookingDateFrom", $('#bookFrom').val());
}
//If user press change limit data goto this loop
$('#dataTableSearchBook').on('length.dt', function () {
var info = table.page.info();
var limit = info.length;
var offset = info.page;
search();
AJ(limit, offset);
});
//if user change page (next/previous)
$('#dataTableSearchBook').on('page.dt', function () {
var info = table.page.info();
var offset = info.page;
var limit = info.length;
search();
AJ(limit, offset);
});
//Go to controller and get data from api to JSON Format
function AJ(limit,offset) {
var a = localStorage.getItem("searchBookingDateFrom");
$.ajax({
url: '@Url.Action("SearchBooking","BookingInfo")',
data: JSON.stringify({
limit: limit,
offset: offset,
BookingDateFrom:a,
}),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#dataTableSearchBook').DataTable({
'data': [
{
"0": data[0],
"1": data[0],
"2": data[0],
"3": data[0],
"4": data[0],
"5": data[0],
"6": data[0],
"7": data[0],
"8": data[0],
"9": data[0],
"10": data[0],
"11": data[0],
"12": data[0],
"13": data[0]
}
]
})
console.log(data)
},
error: function () { console.log('error!!') }
});
当用户按下限制或偏移量然后调用控制器(控制器将从 api 获取数据)但我不知道如何将列表 json 放入我的表中显示为视图层
解决方案
您只需要将数据绑定到相关列。您可以访问此链接以参考更多信息:https ://datatables.net/examples/server_side/post.html
这是一个示例。希望能帮到你,我的朋友:))
public class BookingModel
{
public int BookingId { get; set; }
public string BookingRefNo { get; set; }
public string FullName { get; set; }
public string MobileNo { get; set; }
public string Email { get; set; }
}
[HttpPost]
public IActionResult GetData()
{
List<BookingModel> data = new List<BookingModel>();
for(int i = 1; i < 10; i++)
{
BookingModel obj = new BookingModel
{
BookingId = i,
BookingRefNo = $"00{i}",
FullName = $"A{i}",
MobileNo = $"(00)-{i}",
Email = $"abc{i}@gmail.com"
};
data.Add(obj);
}
return Json(new { success = true, data });
}
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Booking Id</th>
<th>Booking RefNo</th>
<th>FullName</th>
<th>MobileNo</th>
<th>Email</th>
</tr>
</thead>
<tbody></tbody>
</table>
$.post('home/getdata', function (response) {
$('#example').DataTable({
processing: true,
data: response.data,
columns: [
{ data: "bookingId" },
{ data: "bookingRefNo" },
{ data: "fullName" },
{ data: "mobileNo" },
{ data: "email" }
]
});
});
推荐阅读
- mysql - 使用 mySQL 查询 3 个不同的表
- php - PHP Sql导入不起作用
- java - 使用 sharedpreference 将用户名放入其他活动
- idl-programming-language - 在 IDL 中用最少的代码制作数组矩阵
- javascript - javascript encodeURIComponent 和转义?
- java - Spring Webflux 或非阻塞模式不能不利于扩展
- c# - 使用 foreach 获取变换的父/子游戏对象时出错
- python - 时间序列数据框熊猫中的多天明智图
- javascript - 如何使用带有 Django 的所见即所得 HTML Javascript 编辑器将数据传递到数据库。
- python - 如何在 Python 中扫描一个句子