public void ProcessRequest(HttpContext context) { // 一、解析请求参数,此处忽略 // 二、如下为具体处理方式 string returnString = string.Empty; string methodName = context.Request.Form["methodName"]; switch(methodName) case "GetData": returnString = GetData(); break; case "InsertNewRow" returnString = InsertNewRow(); break; .....等等多个case分支 default: break; // 三、向客户端返回结果 context.Response.Write(returnString); }
public void ProcessRequest(HttpContext context) { // 一、解析请求参数,此处忽略其余参数的解析,仅获取方法名 string methodName = context.Request.Form["Action"]; // 二、如下为反射的具体处理方式 Type type = this.GetType(); Object[] params = new Objece[1]; //方法参数,咱们统一将context做为参数,觉得用户数据都封装在其中 MethodInfo method = type.GetMethod(methodName); string returnString = (string)method.Invoke(this,params); // 三、向客户端返回结果 context.Response.Write(returnString); }
public String GetRequest(HttpContext context, String paramName)
{
if (context.Request[paramName] != null)
{
return context.Request[paramName].ToString();
}javascript
return "";
html
}java
/// <summary> /// UserHandler 的摘要说明 /// </summary> public class UserHandler : BaseHandler { /// <summary> /// 用户登陆处理 /// </summary> /// <param name="context"></param> /// <returns></returns> public String Login(HttpContext context) { String strAccount = ""; String strPassword = ""; String strRet; try { //获取页面传值 strAccount = GetRequest(context, "Account"); strPassword = GetRequest(context, "Password"); if (strAccount != "" && strPassword != "") { //简单起见,仅返回传递过来的用户帐号与密码 //在实际应用中利用传递过来的参数值调用业务逻辑层的方法来完成客户端的请求 strRet = String.Format("帐号:{0},密码:{1}", strAccount, strPassword); } else { //返回提示信息 strRet = "未能正确获取参数!"; } return strRet; } catch (Exception ex) { throw ex; } } }
<script type="text/javascript"> $(document).ready(function () { $("#btnLogin").click(function () { var account; var password; account = $("#txtUserName").val(); password = $("#txtPassword").val(); $.ajax({ type: "POST", async: true, url: "Handler/UserHandler.ashx", dataType: "text", data: { Action: "Login", Account: account, Password: password }, success: function (data) { alert(data); }, error: function (xhr) { alert(xhr.statusText); return false; } }); }); }); </script>