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

在一个aspx或ashx页面里进行多次ajax调用的更多相关文章

  1. 在小程序中修改上一个页面里data中的数据调用上一个页面的方法

    //获取已经打开的页面的数组 var pages = getCurrentPages(); //获取上一个页面的所有的方法和data中的数据  var lastpage = pages[pages.l ...

  2. asp.net web 项目 针对aspx和ashx的 IHttpHandlerFactory 开发

    ASP.NET Framework处理一个Http Request的流程: HttpRequest-->inetinfo.exe-->ASPNET_ISAPI.dll-->ASPNE ...

  3. jquery.ajax请求aspx和ashx的异同 Jquery Ajax调用aspx页面方法

    1.jquery.ajax请求aspx 请求aspx的静态方法要注意一下问题: (1)aspx的后台方法必须静态,而且添加webmethod特性 (2)在ajax方法中contentType必须是“a ...

  4. Jquery Ajax调用aspx页面方法

    Jquery Ajax调用aspx页面方法 在asp.net webform开发中,用jQuery ajax传值一般有几种玩法 1)普通玩法:通过一般处理程序ashx进行处理: 2)高级玩法:通过as ...

  5. ASP.NET前台html页面AJAX提交数据后台ashx页面接收数据

    摘要:最近在写网站,好不容易弄好了需求又变了,没错企业的门户网站硬要弄成后台管理系统一样,没办法作为小工的我只能默默的改.前台HTML页面需要提交数据到后台处理,又不能用form表单,于是乎研究了1天 ...

  6. 项目中Ajax调用ashx页面中的Function的实战

    前台页面: 使用几个display=none的空间存储DropdownList中的值,点击Search Button后刷新页面再次给DropdownList赋值使用 <%@ Page Langu ...

  7. aspx、ashx、asmx文件处理请求效率比较

    人生总是面临着许多抉择许多困惑!作为一名“攻城师”或“程序猿”的我们,工作的时候更是如此.你曾经是否苦恼过在系统中使用哪种文件编写客户端请求最合适或最高效呢?aspx.ashx.asmx到底该如何选择 ...

  8. aspx与ashx

    ashx在VS的中文版是新建“一般处理程序”,其实是一个实现类System.Web.IHttpHandler接口的类.而任何一个实现了IHttpHandler接口的类都能作为一个外部请求的目标程序.H ...

  9. 人生的抉择—aspx、ashx、asmx文件处理请求效率比较

    人生总是面临着许多抉择许多困惑!作为一名"攻城师"或"程序猿"的我们,工作的时候更是如此.你曾经是否苦恼过在系统中使用哪种文件编写客户端请求最合适或最高效呢?a ...

随机推荐

  1. 【URAL 1519】Formula 1

    http://acm.timus.ru/problem.aspx?space=1&num=1519 调了好久啊.参考(抄)的iwtwiioi的题解. 如果想要题解,题解在<基于连通性状态 ...

  2. 一次xbuild编译失败的排查

    今天一个待上线服务测试完毕,需要构建CI,按照模板配置好包还原,xbuild编译,报错,错误信息如下: EtcdRegister.cs(8,15): error CS0234: The type or ...

  3. Kinect2.0 for Mac开箱

    前段时间从米国带回来一个Kinect,坑爹地发现需要适配器才能连接电脑.于是又从微软官网下单了适配器.今天终于在Mac上把Kinect装起来跑了,与大家分享一点图片. Kinect驱动安装 Kinec ...

  4. BZOJ 3275: Number

    3275: Number Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 874  Solved: 371[Submit][Status][Discus ...

  5. 安装了ruby后怎么安装sass

    在命令行中输入 ruby -v 查看版本号 先移除默认的https://rubygems.org源,命令为gem sources --remove https://rubygems.org/,按回车 ...

  6. 几种常见的Shell

    Unix/Linux上常见的Shell脚本解释器有bash.sh.csh.ksh等,习惯上把它们称作一种Shell.我们常说有多少种Shell,其实说的是Shell脚本解释器. bash bash是L ...

  7. JQuery常用函数及功能小结

    1.文档加载完成执行函数$(document).ready(function(){  alert("开始了");});2.添加/删除CSS类$("#some-id&quo ...

  8. std::unique_lock<std::mutex> or std::lock_guard<std::mutex> C++11 区别

    http://stackoverflow.com/questions/20516773/stdunique-lockstdmutex-or-stdlock-guardstdmutex The diff ...

  9. JAVA连接SqlServer2008R2和MySql数据库

    问题描述: 下面是有关连接SqlServer2008R2和MySql数据库的封装类 package com.test; import java.sql.Connection; import java. ...

  10. linux -目录结构

    摘自:http://www.comptechdoc.org/os/linux/usersguide/linux_ugfilestruct.html 这个目录结构介绍是我目前看到介绍最全的,有时间在翻译 ...