在一个aspx或ashx页面里进行多次ajax调用

时间:2022-02-02 17:37:50

在用ajax开发asp.net程序里.利用ashx页面与前台页面进行数据交互.但是每个ajax交互都需要一个ashx页面.结果是项目里一大堆ashx页面.使项目难以管理.现在我们就想办法让一个ashx页面里允许多个ajax交互;

前台页面AjaxTest.htm,内容如下

<!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>本页用不同的方式与后台进行交互</title>
    <script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" >

//使用jquery库进行ajax交互
      $(document).ready(function(){

 //进行一个ajax请求,command告诉后台调用哪个方法
         $.get("Handler.ashx",{command:"method1",value:"chentao"},function(data){
            alert(data);
          });

//进行一个ajax请求,command告诉后台调用method2方法

$.get("Handler.ashx",{command:"method2",value:"tangyu"},function(data){

alert(data);
       })
      
    </script>
</head>
<body>

</body>
</html>

后台建立一个Handler.ashx页面 内容如下

<%@ WebHandler Language="C#" class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
  
        if (context.Request["command"]!=null)
            
        {

                //得到前台传过来的command,确定调用哪个方法

string command = context.Request["command"].ToString();
          string data = context.Request["value"].ToString();
         switch (command)
          {
               case "method1":
                 method1(context);
                  break;
              case "method2":
                  method2(context);
                  break;
               default:
                 break;
           }
        }
              
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    public void method1(HttpContext context)
    {
       
        context.Response.Write("hello,"+context.Request["value"].ToString());
       
       
    }
    public void method2(HttpContext context)
    {
               context.Response.Write("hello,"+context.Request["value"].ToString());
    }

}

如果有多个方法,switch  case里的判断将会很多.考虑用更简单的方法.使用反射

<%@ WebHandler Language="C#" class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        if (context.Request["command"] != null)
        {

//
            string command = context.Request["command"].ToString();
            System.Reflection.MethodInfo method = this.GetType().GetMethod(command);
            if (method != null)
            {
                method.Invoke(this, new object[] { context});
            }
        }
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    public void method1(HttpContext context)
    {
  
        context.Response.Write("hello"+context.Request["value"].ToString());
       
       
    }
    public void method2(HttpContext context)
    {

        context.Response.Write("hello,"+context.Request["value"].ToString());
    }

}

使用反射大大简化了程序.

=====================================================

使用aspx页面与ajax交互

新建一个aspx页面 WebMethod.aspx

将WebMethod.aspx页里的多余部分删除,只保留

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebMethod.aspx.cs" Inherits="WebMethod" %>

这一条语句

WebMethod.aspx.cs内容如下

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Web.Services;
using System.Reflection;

public partial class WebMethod : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string methodName = HttpContext.Current.Request.PathInfo.Substring(1);
      // Response.Write(methodName);
        MethodInfo method = this.GetType().GetMethod(methodName);
        if (method != null)
        {
            Response.Write(method.Invoke(this,new object[]{}));
        }
       // Response.Write(GetResult());
       
    }
    [WebMethod(EnableSession=true)]
    public  string GetResult()
    {
        //return "hello";
        if (HttpContext.Current.Request["name"] != null)
        {
            string value = HttpContext.Current.Request["name"].ToString();
            //HttpContext.Current.Request.PathInfo;
            return "{'name':'"+value+"'}";
        }
        else
        {
            return "{name:'error'}";
        }
    }
}

test.html页面与WebMethod.aspx页面进行ajax交互 test.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>使用aspx页面进行交互</title>
    <script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" >
      $(document).ready(function(){

             $.ajax({
             type: "POST",
      
        url: "WebMethod.aspx/GetResult",
        data: "name=chentao",
        dataType: "text",
        success: function(d){
        alert(d);
        }

});
      });
    </script>
</head>
<body>

</body>
</html>