This section describes how to use AJAX to obtain information asynchronously in MVC2.0. In this section, we use AJAX functions in JQUERY to obtain the server time asynchronously.
Main content of this section
1.asp.net mvc 2.0 uses jquery's ajax Function
2. The server-side time and client time are converted to each other using JSON
First, we can see that clicking the server time button on the page will get the time from the server and display it on the page. At this time, the client time remains unchanged.
View the Page code at the view layer.
[Html]
<Head runat = "server">
<Title> User List page </title>
<Script src = ".../Scripts/jquery-1.4.1-vsdoc.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
/**
* Format the time object;
*/
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 = "client time:" + testStr;
}
// Obtain the server time Asynchronously
Function GetTime ()
{
$. Ajax ({
Type: "post ",
Url: "/user/GetTime ",
Cache: false,
Data: {id: "1 "},
Success: function (output ){
If (output = "" | output = undefined ){
Alert ('Return value is blank! ');
}
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 ");
Certificate ('{divserver'{.html ("server time:" + value );
}
},
Error: function (XMLHttpRequest, textStatus, errorThrown)
{
Alert ("data retrieval exception ");
}
});
}
</Script>
</Head>
<Body>
<P>
<Input type = "button" value = "server-side time" onclick = "GetTime ();"/>
<Div id = "divserver">
</Div>
<Div id = "clientDiv">
</Div>
</P>
</Body>
Controller Layer
[Csharp]
Public JsonResult GetTime ()
{
If (Request. IsAjaxRequest ())
{
// If it is an AJAX request
Var info = new Models. Info ();
Info. ID = "13 ";
Return this. Json (info );
}
Else
{
Return null;
}
}
Model Layer
[Csharp]
Public class Info
{
Public string ID
{
Get;
Set;
}
Public DateTime CurTime
{
Get {return DateTime. Now ;}
}
}
From cheese Column