本测试包含2个页面 Ajax.aspx 和 Handler1.ashx
先看看 Ajax.aspx
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function () {
$('#user-ajax').click(function () {
$.get("Handler1.ashx", { method: "method1", txt1: $("#Text1").text() }, function (msg) { $("#Text1").text(msg); } );
//或者 $.post("Handler1.ashx", { method: "method1", txt1: $("#Text1").text() }, function (msg) { $("#Text1").text//(msg); } );
});
});
</script>
</head>
<body>
<input id="user-ajax" type="button" value="click" />
<div id="Text1" style="height:100px;border:1px solid Gray; color:Blue;">initial data</div>
</body>
//说明
// 上面的method对应的键值"method1"是handler1.ashx里面的方法名(函数名),我在handler1.ashx里面写了3个方法可以选择性的使用
//这样我们就可以使用 id 为 user-ajax的按钮 实现页面局部更新了
再看看Handler1.ashx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Jquery
{
/// <summary>
/// Summary description for Handler1
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
String txt = context.Request["txt1"].ToString();
String method = context.Request["method"].ToString();
switch (method)
{
case "method1":
txt= Method1(txt);
break;
case "method2":
txt = Method1(txt);
break;
case "method3":
txt = Method1(txt);
break;
}
context.Response.Write(txt + "Hello World");
}
public string Method1(string para)
{
return para+" is dealed by method 1";
}
public string Method2(string para)
{
return para + " is dealed by method 3";
}
public string Method3(string para)
{
return para + " is dealed by method 3";
}
public bool IsReusable
{
get
{
return false;
}
}
}
}