//一般处理文件--Handler
<%@ WebHandler Language="C#" Class="HandlerPerson" %>
using System;
using System.Web;
public class HandlerPerson : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string Name = context.Request.Params["Name"];
int Id = Convert.ToInt32(context.Request.Params["Id"]);
Person model = new Person(Name, Id);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer() ;
string tep = serializer.Serialize(model);
context.Response.Write(tep);
}
public bool IsReusable {
get {
return false;
}
}
}
//HTML页的代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json.aspx.cs" Inherits="Json" %>
<!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 runat="server">
<title></title>
//导入Ajax类库
<script src="System.Web.Extensions/3.5.0.0/3.5.30729.1/MicrosoftAjax.js" type="text/javascript"></script>
<script language ="javascript" type ="text/javascript">
function person(Name, Id) {
var requst = new Sys.Net.WebRequest();
requst.set_url("HandlerPerson.ashx");
requst.set_httpVerb("POST");
requst.add_completed(OnPersonCompleted);
var requstbody = String.format("name={0}&id={1}", encodeURIComponent(Name), encodeURIComponent(Id));
requst.set_body(requstbody);
requst.invoke();
}
//回调函数
function OnPersonCompleted(response) {
if (response.get_responseAvailable()) {
var personIinof = response.get_object();
alert(String.format ("name{0} id{1}",personIinof.Name,personIinof.Id));
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type ="button" value ="Person" onclick = "person('复旦大学','102');" />
</div>
</form>
</body>
</html>