【轉載】在一個aspx或ashx頁面裡進行多次ajax調用

來源:互聯網
上載者:User

在用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>

 

在用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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.