The client invokes a ashx file (a generic HTTP handler) with an HTML page that returns the custom object in JSON format:
HTML:
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title>ajax Test </title>
<script src= "Js/jquery-1.2.3.js" type= "Text/javascript" ></script><!-here is a reference to the jquery framework->
<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>
handler.ashx File:
Copy Code code 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 ());//serializing objects into JavaScript object Notation (JSON)
Djson. WriteObject (context. Response.outputstream, p1);
}
public bool IsReusable {
get {
return false;
}
}
[datacontract]//to serialize, be sure to add this property
public class Person
{
[The datamember]//property ' DataMember ' is valid only in the ' Properties, indexer, field ' declaration.
public string Name= "no celebrities";
[DataMember]
public string age= "0";
public override string ToString ()
{
Return "Name:" + name + "Age:" + ages;
}
Public person (String name,string age)/Custom class person
{
This. name = name;
This. Age = age;
}
Public person ()
{ }
}
}