Fork me on GitHub

jQuery/asp.net mvc DateTime 的处理

在Javascript中的DateTime需要使用new Date(318326400000),asp.net mvc返回的Json时间格式变成了/Date(318326400000)/
 
jQuery.ajax() 函数消费的Json数据的Date类型可以通过jQuery 1.2.6以上版本所增加的 jQuery.ajax.dataFilter

第一步通过jQuery.ajax()的dataFilter函数预处理asp.net datetime 对象到本地的javascript对象
 $.ajax({
                type: "POST",
                dataType: "json", //数据格式:JSON
                url: '/MyProject/SearchMailInfoJson', //目标地址
                data: "page=" + pageindx + buildWhere(),
                beforeSend: function() { $("#divload").show(); $("#Pagination").hide(); }, //发送数据之前
                complete: function() { $("#divload").hide(); $("#Pagination").show(); }, //接收数据完毕
                dataFilter: function(data, type) {
                    return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
                },
                success: function(json) {
                    $("#list-table tr:gt(0)").remove();
                    $.each(json, function(i, item) {
                        if (item["SendTime"] == null) {
                            item["SendTime"] = "";
                        }
                        var trs = "";
                        trs += "<tr style='font-weight: '> <td align='center'>" + item["EmailSubject"];
                        trs += "</td><td align='center' style='word-wrap:break-word;word-break:break-all;'>";
                        trs += item["MessageTo"] + "</td><td>" + item["MessageFrom"] + "</td>";
                        trs += "<td align='left'>" + item["EmailCC"] + "</td><td align='center'>" + item["MailType"] + "</td>";
                        trs += "<td align='center'>" + dateFormat(item["ArrivedDateTime"], "yyyy-mm-dd HH:MM:ss") + "</td>";
                        trs += "<td align='center'>" + item["Status"] + "</td>";
                        trs += "<td align='center'>" + dateFormat(item["SendTime"], "yyyy-mm-dd HH:MM:ss") + "</td>";
                        trs += "<td><a href='javascript:showPopWin('效果预览', 'SendMailPreview?sysId=" + item["SystemID"] + "&mailID=" + item["ID"] + "', 600, 600, null,true,true);>预览</a></td><tr>";
                        tbody += trs;
                    });                
                  
                    $("#list-table").append(tbody);

                    $("#list-table tr:gt(0)").hover(function() {
                        $(this).addClass('mouseover');
                    }, function() {
                        $(this).removeClass('mouseover');
                    });
                }
            });
第二步处理javascript的Date的字符串表示,类似于.net DateTime.ToString(). 这可以使用另一个javascript 时间格式库,文档参看 http://blog.stevenlevithan.com/archives/date-time-format

http://www.overset.com/2008/07/18/simple-jquery-json-aspnet-webservice-datetime-support/

posted @ 2009-07-24 12:48  张善友  阅读(4770)  评论(1编辑  收藏  举报