Html code:
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "/javascript/jquery-1.4.js"> </script>
<Script type = "text/javascript">
Function jsonTest1 ()
{
$. Ajax ({
Url: "Handler. ashx ",
Data: {"type": "ajax "},
Datatype: "json ",
Type: "get ",
Success: function (data)
{
Document. getElementById ('div1 '). innerHTML = data; // A json string is returned because the mime type is text.
}
});
}
Function jsonTest2 ()
{
$. GetJSON (
'Handler. ashx ',
{'Type': 'json', 'name': 'qixuejia '}, // type format
Function (data)
{
For (var I = 0; I <data. length; I ++)
{
Alert (data [I] ["UserId"])
}
}
);
}
</Script>
<Form id = "form1" runat = "server">
<Div id = "div1">
</Div>
<Input type = "button" value = "jQuery. ajax ()" onclick = "jsonTest1 ()"/>
<Input type = "button" value = "jQuery. getJSON ()" onclick = "jsonTest2 ()"/>
</Form>
Ashx handler: to return an object in json format, set the mime type to "application/json ".
View the jQuery source file and you can see that getJSON is implemented as follows:
GetJSON: function (url, data, callback ){
Return jQuery. get (url, data, callback, "json ");
},
Copy codeThe Code is as follows:
Public void ProcessRequest (HttpContext context)
{
If (context. Request. Params ["type"]. Equals ("ajax "))
{
Context. Response. ContentType = "text/plain ";
}
Else
{
Context. Response. ContentType = "application/json ";
}
GetInfo (context );
}
Public bool IsReusable
{
Get
{
Return false;
}
}
Public void GetInfo (HttpContext context)
{
System. Collections. Generic. List <UserInfo> listUser = UserInfoManage. GetUserInfoBySQL ("Select Top 5 * From Userinfo ");
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter ();
TimeConverter. DateTimeFormat = "yyyy '-'mm'-'dd''' HH': 'mm': 'ss ";
String ResJsonStr = JsonConvert. SerializeObject (listUser, timeConverter );
Context. Response. Write (ResJsonStr );
}