DataTables在ajax获取json数据后,处理数据中日期(datetime)类型错误
引用了:https://blog.youkuaiyun.com/h273979586/article/details/77913896 的解决方式
- 问题截图及调试数据
上图中的数据呈现毫秒计的格式,原因是在MVC框架下,通过使用datatables来呈现数据库表格内容,期间使用了ajax,而代码中又从数据库返回了json格式的数据,在传回的时候,解析出错。
第一部分:初始化datatable并设定Ajax中的URL
<!-- 初始化 DataTables -->
<script>
$(document).ready(function () {
$('#example').dataTable({
"bPaginate": true,
ajax: {
//调用URL中的ACTION方法
url: '@Url.Action("GetAllData", "AjaxTest")',
},
columns: [
{
"name": "Title",
"data": "Title",
}, {
"name": "ReleaseDate",
"data": "ReleaseDate"
}, {
"name": "Genre",
"data": "Genre",
}, {
"name": "Price",
"data": "Price",
}, {
"name": "Rating",
"data": "Rating",
}
]
});
});
</script>
第二部分:URL调用的ACTION方法中返回Json数据
public JsonResult GetAllData()
{
var MoviesData = new List<Movie>();
//获取所有内容
var movies = from m in db.Movies
select m;
foreach (var item in movies.ToList())
{
MoviesData.Add(item);
}
//返回json数据到Index界面
return Json(new
{
iTotalRecords = MoviesData.Count(),
iTotalDisplayRecords = MoviesData.Count(),
data = MoviesData
}, JsonRequestBehavior.AllowGet);
}
- 处理方式
修改第一部分代码:
<script>
$(document).ready(function () {
$('#example').dataTable({
"bPaginate": true,
ajax: {
url: '@Url.Action("GetAllData", "AjaxTest")',
},
columns: [
{
"name": "Title",
"data": "Title",
}, {
"name": "ReleaseDate",
"data": "ReleaseDate",
//电影上映日期的格式修改
"render": function ChangeDateFormat(cellval) {
var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
}
}, {
"name": "Genre",
"data": "Genre",
}, {
"name": "Price",
"data": "Price",
}, {
"name": "Rating",
"data": "Rating",
}
]
});
});
</script>
- 处理结果