The client uses an HTML page to call an ashx file (generally HTTP Processing
Program ), Return a custom object in JSON format:
HTML: CopyCode The Code is as follows: <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Ajax test </title>
<SCRIPT src = "JS/jquery-1.2.3.js" type = "text/JavaScript"> </SCRIPT> <! -The jquery framework is referenced here->
</Head>
<Body>
<SCRIPT type = "text/JavaScript">
$ (Document). Ready (function (){
$ ("# Button2"). Click (function (){
VaR url = "handler. ashx? & Name = "+ $ (" # text1 "). Val () +" & age = "+ $ (" # text2 "). Val ();
$. Get (URL, function (result ){
VaR OBJ = eval ("(" + Result + ")");
Alert ("name:" + obj. Name + "\ n" + "Age:" + obj. Age );
})
})
})
</SCRIPT>
<Input id = "button2" type = "button" value = "button"/> <SPAN lang = "ZH-CN"> Name: </span> <input id = "text1"
Type = "text"/> <SPAN lang = "ZH-CN"> Age: </span>
<Input id = "text2"
Type = "text"/>
</Body>
</Html>
Handler. ashx file: Copy code The Code is as follows: <% @ webhandler Language = "C #" class = "handler" %>
Using system;
Using system. Web;
Using system. runtime. serialization. JSON;
Using system. collections;
Using system. runtime. serialization;
Public class handler: ihttphandler {
Public void processrequest (httpcontext context)
{
Context. response. contenttype = "text/plain ";
String name = context. Request. Params ["name"]. tostring ();
String age = context. Request. Params ["Age"]. tostring ();
Person p1 = new person (name, age );
Datacontractjsonserializer djson = new datacontractjsonserializer (p1.gettype (); // serialize the object to JavaScript Object Notation (JSON)
Djson. writeobject (context. response. outputstream, P1 );
}
Public bool isreusable {
Get {
Return false;
}
}
[Datacontract] // This attribute must be added for serialization
Public class person
{
[Datamember] // The attribute "datamember" is valid only in the "property, indexer, field" declaration.
Public string name = "";
[Datamember]
Public String age = "0 ";
Public override string tostring ()
{
Return "name:" + name + "Age:" + age;
}
Public Person (string name, string age) // custom class person
{
This. Name = Name;
This. Age = age;
}
Public Person ()
{}
}
}