The client calls an ashx file (generally an http handler) on an html page and returns a custom object in json format:
Html :--------------------------------------------------
<! 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 :--------------------------------------------------------
<% @ 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 ()
{}
}
}