asp.net mvc 2.0异步获取服务器时间
这一节给大家讲下MVC2.0中怎样使用AJAX来异步获取信息,本节我们使用JQUERY中的AJAX函数异步获取服务器端的时间。
本节的主要内容
1.asp.net mvc 2.0中使用jquery的ajax函数
2.服务器端时间和客户端时间通过JSON进行相互转换
首先,我们看下效果图,点击页面上的 服务器时间按钮,会从服务器端获取时间,并显示在页面上,此时客户端时间是不变的
看下 view层的页面代码
[html]
<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层
[csharp]
public JsonResult GetTime()
{
if (Request.IsAjaxRequest())
{
//如果为AJAX请求
var info = new Models.Info();
info.ID = "13";
return this.Json(info);
}
else
{
return null;
}
}
model层
[csharp]
public class Info
{
public string ID
{
get;
set;
}
public DateTime CurTime
{
get { return DateTime.Now; }
}
}
摘自 奶酪专栏