利用jquery对MVC输出的json对象进行处理,修改日期格式及取字符串的一部分

来源:互联网 发布:windows相对路径写法 编辑:程序博客网 时间:2024/05/08 12:51

mvc从数据库中获取的对象如下:

[{"Name":"Simulation-shengxuefei-1492676375126","ExamResult":1,"ExamTime":11502,"CreateTime":"\/Date(1492676375437)\/","GID":"7a38b744-2344-4b35-a593-d8c58bf0b48b"},{"Name":"Simulation-shengxuefei-1492670196976","ExamResult":1,"ExamTime":6,"CreateTime":"\/Date(1492670197077)\/","GID":"3ce16e58-862c-40ae-92ab-301f0786538d"},{"Name":"Simulation-shengxuefei-1492669653692","ExamResult":0,"ExamTime":0,"CreateTime":"\/Date(1492669653990)\/","GID":"493b8470-ed17-4712-82ae-001dd10e61f9"},{"Name":"Simulation-shengxuefei-1492669796322","ExamResult":0,"ExamTime":0,"CreateTime":"\/Date(1492669796460)\/","GID":"f5f99680-3317-4cfc-b855-d9df9b1573b7"}]

这里的Name只需要Simulation-shengxuefei-1492676375126 中的shengxuefei ,而 CreateTime 则需要转换日期格式从 Date(1492676375437)/ 转换为yyyy-MM-dd hh:mm


 这里要说道为什么不在服务器端直接转换格式后再输出?这是因为服务器端的数据获取用的是linq。而linq to sql不能直接使用C#的字符串处理函数及日期转换函数。

首先 javascript 增加一日期扩展:

// 对Date的扩展,将 Date 转化为指定格式的String// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)// 例子:// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18Date.prototype.Format = function (fmt) { //author: meizz    var o = {        "M+": this.getMonth() + 1, //月份        "d+": this.getDate(), //日        "h+": this.getHours(), //小时        "m+": this.getMinutes(), //分        "s+": this.getSeconds(), //秒        "q+": Math.floor((this.getMonth() + 3) / 3), //季度        "S": this.getMilliseconds() //毫秒    };    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));    for (var k in o)        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));    return fmt;}

然后利用jquery 的 $.each循环处理:

 $.post("/member/GetCompletedSimulation", {}, function (data) {                    //console.info(data);                    $.each(data, function (index, item) {                        item.Name = item.Name.split('-')[1];                        var thisTime = parseInt(item.CreateTime.replace(/\D/igm, ""));                        item.CreateTime = new Date(thisTime).Format("yyyy-MM-dd hh:mm");                    });                    //console.info(data);                    page.VM.CompeteVM = ko.mapping.fromJS(data, {}, page.VM.CompeteVM);                });

这样处理过后就可以使用knockoutjs赋值给页面元素了。

page.VM.CompeteVM = ko.mapping.fromJS(data, {}, page.VM.CompeteVM);

0 0
原创粉丝点击