Code for processing json data using jQuery getJSON

Source: Internet
Author: User

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 );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.