asp.net mvc 2.0 异步获取服务器时间

来源:互联网 发布:推荐算法 数据集 编辑:程序博客网 时间:2024/05/17 09:28

 

  这一节给大家讲下MVC2.0中怎样使用AJAX来异步获取信息,本节我们使用JQUERY中的AJAX函数异步获取服务器端的时间。

  本节的主要内容

    1.asp.net mvc 2.0中使用jquery的ajax函数

    2.服务器端时间和客户端时间通过JSON进行相互转换

 

1. ajax函数的用法

首先,我们看下效果图,点击页面上的 服务器时间按钮,会从服务器端获取时间,并显示在页面上,此时客户端时间是不变的

 

看下 view层的页面代码

在VIEW页面中,我们发送请求到controller层,然后获取controller层返回的JSON对象

<head runat="server">    <title>用户列表页</title>    <script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>    <script type="text/javascript">        /**        * 时间对象的格式化;        */        Date.prototype.format = function (format) {            /*            * eg:format="YYYY-MM-dd hh:mm:ss";            */            var o = {                "M+": this.getMonth() + 1,  //month                "d+": this.getDate(),     //day                "h+": this.getHours(),    //hour                "m+": this.getMinutes(),  //minute                "s+": this.getSeconds(), //second                "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter                "S": this.getMilliseconds() //millisecond            }            if (/(y+)/.test(format)) {                format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));            }            for (var k in o) {                if (new RegExp("(" + k + ")").test(format)) {                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));                }            }            return format;        }              window.onload = function () {            var testDate = new Date();            var testStr = testDate.format("yyyy-MM-dd hh:mm:ss");            document.getElementById("clientDiv").innerHTML ="客户端时间:"+ testStr;        }        //异步获取服务器时间        function GetTime()         {            $.ajax({                type: "post",                url: "/user/GetTime",                cache: false,                data: { id: "1" },                success: function (output) {                    if (output == "" || output == undefined) {                        alert('返回值为空!');                    }                    else {//                        value = new Date(parseInt(output.CurTime.replace("/Date(", "").replace(")/", ""), 10));                         value = new Date(parseInt(output.CurTime.substr(6)));                        value = value.format("yyyy-MM-dd hh:mm:ss");                        $('#divserver').html("服务器时间:" + value);                    }                },                error: function (XMLHttpRequest, textStatus, errorThrown)                 {                    alert("获取数据异常");                }            });                }    </script></head><body>  <p>  <input  type="button" value="服务器端时间" onclick="GetTime();"/>        <div id="divserver">               </div>               <div id="clientDiv">                </div>        </p></body>


 

controller层:

在controller层我们返回一个JSON对象,使用Request.IsAjaxRequest判断是否是一个AJAX请求,如果不为AJAX请求,返回NULL,

如果是AJAX请求,返回一个JSON对象。

     public JsonResult GetTime()        {            if (Request.IsAjaxRequest())            {                //如果为AJAX请求                var info = new Models.Info();                info.ID = "13";                return this.Json(info);            }            else            {                return null;            }                   }


 

 

model层:

info的CurTime属性里面记录了当前服务器的时间。

public class Info    {        public string ID        {            get;            set;        }        public DateTime CurTime        {            get { return DateTime.Now; }        }           }


 通过以上代码就能获取到服务器的时间了。

 

 2.服务器端时间和客户端时间的转换

  实际上服务器端的时间和客户端时间的转换是一个比较棘手的地方。

 如果服务器端的curtime是一个string类型,这样是没问题的。

 但是服务器的时间是datetime类型,通过AJAX调用,返回给客户端是这样格式的,/Date(1242357713797+0800)/,这样客户端就没法识别,需要转换,

通过以下几种方法可进行转换:

  1.    value = new Date(parseInt(output.CurTime.replace("/Date(", "").replace(")/", ""), 10));

  2.   value = new Date(parseInt(output.CurTime.substr(6)));

   更多转换的方法可参照以下链接,本人认为以下链接不错,特贴出来供大家参考

  http://www.cnblogs.com/shanyou/archive/2009/07/24/1530088.html

 http://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format

 http://stackoverflow.com/questions/6351464/mvc3-inconsistent-json-datetime-behaviour-between-jsonresult-and-jsonvalueprovid

 http://www.cnblogs.com/coolcode/archive/2009/05/22/1487254.html

 

 

 

原创粉丝点击