• jQuery 表单提交和一般处理程序


     最近做的项目有关于post、get提交数据到后台,select联动。 可是每次都忘记怎么写,每次都要在网上百度,于是想出写个自己的博客以便于以后自己不知道的时候能够快速的翻来查看找到相关的内容。  

    1、前段js 其中使用到的CommonData.ashx方法将在2中出现

    <%--C#的一般处理程序及Jquery post提交数据  一般处理程序返回json数据--%>
    <select id="YParent" name="YParent" onchange="changeDep()" class="selecta"></select>
    <select id="S_LEGALINDUSTRY" name="S_LEGALINDUSTRY" class="selecta"></select>
    <script type="text/javascript">
    
       jQuery(document).ready(function () {
            load_group();//动态加载数据
        });
       //一级数据
       function load_group() {
           var str = "<option value=0>请选择</option>";
           jQuery.ajax({
               type: "POST",
               url: "/Manager/Handler/CommonData.ashx",
               data: "flag=First",
               success: function (data) {
                  if (data.status == "true") {
                       for (var i = 0; i < data.msg.length; i++) {
                          var deptname = data.msg[i].Key;
                          var id = data.msg[i].Value;
                          str = str + "<option value=" + id + ">" + deptname + "</option>";
                       }
                       jQuery("#YParent").append(str);
                    }
                  },
                dataType: "json"
              });
         };
        //一级点击的时候查询二级数据并添加到二级页面中
        function changeDep() {
           jQuery("#S_LEGALINDUSTRY").empty();
           var str = "<option value=0>请选择</option>";
           var groupId = jQuery("#YParent").val();
           if (groupId == "0") return;
           jQuery.ajax({
              type: "POST",
              url: "/Manager/Handler/CommonData.ashx",
              data: "flag=Two&groupId=" + groupId,
              success: function (data) {
                  if (data.status == "true") {
                     for (var i = 0; i < data.msg.length; i++) {
                         var deptname = data.msg[i].Key;
                         var id = data.msg[i].Value;
                         str = str + "<option value=" + id + ">" + deptname + "</option>";
                     }
                     jQuery("#S_LEGALINDUSTRY").append(str);
                    }
                  },
                 dataType: "json"
             });
            }
    </script>
    View Code
    $.post("test.aspx", $("#testform").serialize()); //直接传递表单对象
    $.post("test.aspx", { 'choices[]': ["Jon", "Susan"] }); //传递复杂的json数据
    $.post("test.aspx", { name: "John", time: "2pm" } );//传递简单的json数据
    
    --json
    $.post("test.aspx", { "func": "getNameAndTime" },
       function(data){
         alert(data.name); 
         console.log(data.time); 
       }, "json");
    --xml
    $.post("test.php", { name: "John", time: "2pm" },
       function(data){
         process(data);
       }, "xml");

    2、CommonData.ashx一般处理程序

    /// <summary>
        /// CommonData 的摘要说明
        /// </summary>
        public class CommonData : IHttpHandler, System.Web.SessionState.IRequiresSessionState
        {
    
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                var flag = context.Request["flag"];
                switch (flag)
                {
                    case "First":
                        First(context);
                        break;
                    case "Two":
                        Two(context);
                        break;
                    default:
                        break;
                }
    
            }
    
            private void Two(HttpContext context)
            {
                string groupId = context.Request["groupId"] + "";
                using (LsTransEntities data = new LsTransEntities())
                {
                    List<DictionaryEntry> industriesTypeList = new List<DictionaryEntry>();
                    var query = from item in data.S_CINDUSTRYCLASSIFICATION
                                where item.CODE.Trim().Length > 1
                                where item.CODE.StartsWith(groupId)
                                //where item.CODE != "511100"
                                select new { key = item.CODE + item.NAME, value = item.CODE.Trim() };
                    //将数据循环添加到industriesTypeList中
                    query.ToList().ForEach(p => industriesTypeList.Add(new DictionaryEntry(p.key, p.value.Trim())));
                    //industriesTypeList中的数据转换为json格式的数据
                    //Newtonsoft.Json.JsonConvert.SerializeObject
                    string json = Newtonsoft.Json.JsonConvert.SerializeObject(industriesTypeList);
                    context.Response.Write("{"status":"true", "msg":" + json + "}");
                }
            }
    
            private void First(HttpContext context)
            {
               
                using (LsTransEntities data = new LsTransEntities())
                {
                    List<DictionaryEntry> industriesTypeList = new List<DictionaryEntry>();
                    var query = from item in data.S_CINDUSTRYCLASSIFICATION
                                where item.CODE.Trim().Length == 1
                                //where item.CODE != "511100"
                                select new { key = item.CODE + item.NAME, value = item.CODE.Trim() };
                    //将数据循环添加到industriesTypeList中
                    query.ToList().ForEach(p => industriesTypeList.Add(new DictionaryEntry(p.key, p.value.Trim())));
                    //industriesTypeList中的数据转换为json格式的数据
                    string json = Newtonsoft.Json.JsonConvert.SerializeObject(industriesTypeList);
                    context.Response.Write("{"status":"true", "msg":" + json + "}");
                }
            }
    
        }
    View Code

    3、直接调用aspx中的方法FileService.aspx 将在4中出现

     ==

    $.ajax({
         url: "FileService.aspx?method=LoadFiles&folderId=" + folderId,
         success: function (text) {
             var files = mini.decode(text);
             refreshFiles(files);
          }
     });

     4、aspx的后台写法 使用Invoke 方法

    //.aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileService.aspx.cs" Inherits="FileService" %>
    
    
    //.cs
    public partial class FileService : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //获取传递过来的方法名称
            String methodName = Request["method"];
            //判断方法名称是否为空
            if (String.IsNullOrEmpty(methodName)) return;
    
            Type type = this.GetType();
            //获取当前类的指定方法
            MethodInfo method = type.GetMethod(methodName);
            method.Invoke(this, null);
        }
        public void LoadFolders() 
        {
            String id = Request["id"];
            if (String.IsNullOrEmpty(id)) id = "-1";
    
            //获取下一级节点
            String sql = "select * from plus_file where folder = 1 and pid = '" + id + "' order by updatedate";
            ArrayList folders = Test.DBUtil.Select(sql);
    
            //判断节点,是否有子节点。如果有,则处理isLeaf和expanded。
            for (int i = 0, l = folders.Count; i < l; i++)
            {
                Hashtable node = (Hashtable)folders[i];
                String nodeId = node["id"].ToString();
    
                node["isLeaf"] = false;
                node["expanded"] = false;            
            }
    
            //返回JSON
            String json = Test.JSON.Encode(folders);
            Response.Write(json);
        }
        public void LoadFiles()
        {
            String folderId = Request["folderId"];
            
            String sql = "select * from plus_file where pid = " + folderId + " and folder = 0 order by updatedate";
            ArrayList files = Test.DBUtil.Select(sql);
    
            String json = Test.JSON.Encode(files);
            Response.Write(json);
        }
    }
    View Code

    5、一般处理程序的另一种写法 使用Invoke 方法

    public class ImportExcel : IHttpHandler, System.Web.SessionState.IRequiresSessionState
        {
            private HttpResponse Response = HttpContext.Current.Response;
            private HttpRequest Request = HttpContext.Current.Request;
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                var flag = Request["flag"];
                var method = GetType().GetMethod(flag);
                method.Invoke(this, null);
            }
         public void LoadFiles()
          {
              String folderId = Request["folderId"];
              String sql = "select * from plus_file where pid = " + folderId + " and folder = 0 order by updatedate";
              ArrayList files = Test.DBUtil.Select(sql);
     
              String json = Test.JSON.Encode(files);
              Response.Write(json);
          }
    }
    View Code

    注意: 4、5他们之间有相同之处 也有不同之处

      a>相同于 都是用了Invoke方法  

           b>不同之处 5是一般处理程序,而4则不是一般处理程序

    使用Invoke 少了好多switch

  • 相关阅读:
    字符编码常识及问题解析
    leptonica 学习笔记2——pixBackgroundNormSimple
    用GitLab Runner自动部署GitBook并不难
    使用Docker搭建简易的 Java Web 环境
    ionic button笔记
    学习Sass之安装Sass(一)
    Exploring Ionic Lists
    Using the Cordova Camera API
    ionic介绍
    angularjs2 学习笔记(六) Form
  • 原文地址:https://www.cnblogs.com/lovable/p/7122337.html
Copyright © 2020-2023  润新知