knockout获取服务端传来的json数据,日期数据的处理

首先要创建mapping对象:

var mappingOption = {
    'CreateTime': {
        
        create: function (options) {
            var thisTime = parseInt(options.data.replace(/\D/igm, ""));
            return ko.observable(options.data == null ? null : new Date(thisTime).Format('yyyy-MM-dd hh:mm:ss'));
        },
        update: function (options) {
            var thisTime = parseInt(options.data.replace(/\D/igm, ""));
            return options.data == null ? null : new Date(thisTime).Format('yyyy-MM-dd hh:mm:ss');
        }
    }
};

需要强调的是CreateTime是自服务端传来的数据字段名,当然对于你项目的应用,你可能改变了名称,你要把createtime时间名称换为你项目相对应的时间名称。

用到的Format函数:

Date.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;
}

使用:

  $.post("/m/operator/GetMyTaskList", { page: 1, name: $("#name").val(), complete: $("#complete").val() }, function (data) {
                //page.VM.TaskVM(data);
                ko.mapping.fromJS(data, mappingOption, page.VM.TaskVM);
            });


猜你喜欢

转载自blog.csdn.net/sxf359/article/details/78093618