• 推荐
  • 评论
  • 收藏

jquery Ajax调用asmx和ashx代码示例三级联动

2022-11-11    6015次浏览

html&js

<%@ Page Language="C#" MasterPageFile="~/SaleApp/MasterPage.Master" AutoEventWireup="true" CodeBehind="NewSelBreed.aspx.cs" Inherits="WebApp.SaleApp.BreedManage.NewSelBreed" Title="药品第二种搜索方式" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeaderPlaceHolder1" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!--操作区-->
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td height="26">
                当前位置:<a href="../Default.aspx">系统首页</a> > 品种管理 > 选择库存药品</td>
            <td align="right">
                <a href="#"></a>
            </td>
        </tr>
    </table>
     <table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#a7c4db" class="p3">
                <tr class="color3">
                    <td height="40" background="../images/ss_bg.gif" align="center" id="SearchPanel">
                        名称
                        <input name="txtProcuctName" id="txtProductName" type="text" class="formbk8" 
                            runat="server" /> 
                        主治
                        <input name="txtMajorFunction" id="txtMajorFunction"   type="text" class="formbk8" 
                            runat="server" /> 
                        <select name="ddlFirstCategory" id="ddlFirstCategory"   runat="server">
                          <option value="-1" selected="selected">大类全部</option>
                          <option value="中药">中药</option>
                          <option value="化学药品">化学药品</option>
                          <option value="非药品">非药品</option>
                        </select>
                         
                        <select name="ddlFunctionSys" id="ddlFunctionSys" runat="server" >
                          <option value="-1" selected="selected">治疗系统</option>
                         
                        </select>
                         
                        <select id="ddlSecondCategory" name="ddlSecondCategory" runat="server" >
                          <option value="-1" selected="selected">亚类全部</option>
                        </select> 
                        <select id="ddlDosageform" name="ddlDosageform" runat="server" >
                          <option value="-1" selected="selected">剂型全部</option>
                        </select><br />
                        OTC
                        <select id="ddlOTC" name="ddlOTC" runat="server" >
                          <option value="-1" selected="selected">全部</option>
                          <option value="0">否</option>
                           <option value="甲">甲</option>
                            <option value="乙">乙</option>
                        </select>
                          
                         独家品种
                        <select id="ddlExclusiveProduct" name="ddlExclusiveProduct" runat="server" >
                          <option value="-1" selected="selected">全部</option>
                          <option value="1">是</option>
                          <option value="0">否</option>
                        </select>  
                         医保药物
                        <select id="ddlInsuranceProduct" name="ddlInsuranceProduct" runat="server" >
                          <option value="-1" selected="selected">全部</option>
                          <option value="1">是</option>
                          <option value="0">否</option>
                        </select>  
                         中药保护
                        <select id="ddlProtectProduct" name="ddlProtectProduct" runat="server" >
                          <option value="-1" selected="selected">全部</option>
                          <option value="1">是</option>
                          <option value="0">否</option>
                        </select>  
                         基本药物
                        <select id="ddlPrimaryProduct" name="ddlPrimaryProduct" runat="server" >
                          <option value="-1" selected="selected">全部</option>
                          <option value="1">是</option>
                          <option value="0">否</option>
                        </select>  
                                               <input name="btnSearch" type="button" class="cxbtn" value="查询" onclick="Search()" style="cursor: hand" />
                             

                    </td>
                </tr>
            </table>
    <table width="820" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td style="height: 1px">
            </td>
        </tr>
    </table>
    <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#b4cdf0"
        class="p3">
        <tr class="color3">
            <td align="center" bgcolor="#e8eefa" style=" 87px; height: 22px">
                产品名称</td>
            <td align="center" bgcolor="#e8eefa" style=" 91px; height: 22px">
                剂型</td>
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                产品大类</td>
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                治疗系统</td>
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                亚类</td>
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                独家产品</td>           
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                医保药品</td>            
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                基本药物</td>
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                OTC</td>
            <td align="center" bgcolor="#e8eefa" style="height: 22px">
                中药保护品种</td>
            <td align="center" bgcolor="#e8eefa" style="height:22px">
                查看</td>            
        </tr>
        <asp:Repeater ID="repData" runat="server">
            <ItemTemplate>
                <tr class="p5">                    
                    <td height="20" align="left" bgcolor="white">
                        <%#Eval("ProductName")%>
                    </td>
                    <td height="20" align="left" bgcolor="white">
                        <%#Eval("Dosageform")%>
                    </td>
                    <td height="20" align="center" bgcolor="white">
                        <%#Eval("FirstCategory")%>
                    </td>
                    <td height="20" align="center" bgcolor="white">
                        <%#Eval("FunctionSys")%>
                    </td>
                    <td height="20" align="center" bgcolor="white">
                        <%#Eval("SecondCategory")%>
                    </td>
                    <td height="20" align="center" bgcolor="white">
                        <%#((Eval("ExclusiveProduct").ToString()=="1")?"是":"否")%>
                    </td>
                    
                    <td height="20" align="center" bgcolor="white">
                        <%#((Eval("InsuranceProduct").ToString() == "1")?"是":"否")%>
                    </td>
                    
                    <td height="20" align="center" bgcolor="white">
                        <%#((Eval("PrimaryProduct").ToString() == "1")?"是":"否")%>
                    </td>
                    <td height="20" align="center" bgcolor="white">
                        <%#((Eval("OTC").ToString() == "0") ? "否" : Eval("OTC").ToString())%>
                    </td>                    
                    <td height="20" align="center" bgcolor="white">
                        <%#((Eval("ProtectProduct").ToString() == "1")?"是":"否")%>
                    </td>               
                    <td height="20" align="center" bgcolor="white" title="查看该药品的不同批号类型">
                        <span class="green" style="cursor: hand">
                           <input type="button" class="cxbtn" onclick="<%#Eval("LookScript") %>" value="查看" />
                        </span>
                    </td>
                </tr>
            </ItemTemplate>
            <AlternatingItemTemplate>
                <tr class="p5">
                    <td height="20" align="left" bgcolor="#f9fbfe">
                        <%#Eval("ProductName")%>
                    </td>
                    <td height="20" align="left" bgcolor="#f9fbfe">
                        <%#Eval("Dosageform")%>
                    </td>
                    <td height="20" align="center" bgcolor="#f9fbfe">
                        <%#Eval("FirstCategory")%>
                    </td>
                    <td height="20" align="center" bgcolor="#f9fbfe">
                        <%#Eval("FunctionSys")%>
                    </td>
                    <td height="20" align="center" bgcolor="#f9fbfe">
                        <%#Eval("SecondCategory")%>
                    </td>
                    <td height="20" align="center" bgcolor="#f9fbfe">
                        <%#((Eval("ExclusiveProduct").ToString() == "1")?"是":"否")%>
                    </td>                   
                    <td height="20" align="center" bgcolor="#f9fbfe">
                        <%#((Eval("InsuranceProduct").ToString() == "1")?"是":"否")%>
                    </td>                    
                    <td height="20" align="center" bgcolor="#f9fbfe">
                        <%#((Eval("PrimaryProduct").ToString() == "1")?"是":"否")%>
                    </td>
                    <td height="20" align="center" bgcolor="#f9fbfe">
                         <%#((Eval("OTC").ToString() == "0") ? "否" : Eval("OTC").ToString())%>
                    </td>
                     <td height="20" align="center" bgcolor="#f9fbfe">
                        <%#((Eval("ProtectProduct").ToString() == "1")?"是":"否") %>
                    </td>
                    <td height="20" align="center" bgcolor="#f9fbfe"  title="查看该药品的不同批号类型">
                        <span class="green" style="cursor: hand">
                            <input type="button" class="cxbtn" onclick="<%#Eval("LookScript") %>" value="查看" />
                        </span>
                    </td>
                   
                </tr>
            </AlternatingItemTemplate>
        </asp:Repeater>
    </table>
    <table width="100%" height="47" border="0" cellpadding="0" cellspacing="0">
          <tr>
            <td width="3%" align="center"> </td>
            <td width="97%" align="left">
                <webdiyer:AspNetPager ID="AspNetPager1" runat="server" HorizontalAlign="Left" CustomInfoHTML='目前共有<font color="red">%RecordCount%</font>条记录                 当前 <font color="red">%CurrentPageIndex%</font> / %PageCount%页'
                    FirstPageText="首页" LastPageText="尾页" NextPageText="下一页" PageIndexBoxType="TextBox"
                    PrevPageText="上一页" ShowCustomInfoSection="Left" ShowPageIndex="False" ShowPageIndexBox="Always"
                    TextBeforePageIndexBox="跳转到: " OnPageChanged="AspNetPager1_PageChanged" PageSize="10" PageIndexBoxClass="formbk8" SubmitButtonClass="cxbtn"
                    NavigationToolTipTextFormatString="{0}" CssClass="a2" AlwaysShow="True" UrlPaging="true"  SubmitButtonText="Go">
                </webdiyer:AspNetPager>
            </td>
          </tr>
        </table>
    <script type="text/javascript" language="javascript" >    
     var Go = function()
     {
        if(window.event.keyCode == '13')
            Search();
     }
     var Search = function()
     {
        if($.trim($('#<%=txtProductName.ClientID %>').val()) == "" 
        && $.trim($('#<%=txtMajorFunction.ClientID%>').val()) == "" 
        && $('#<%=ddlFirstCategory.ClientID %>').val()== "-1")
        {
            alert('请至少输入一个查询条件\n1.药品名称\n2.主治功能\n3.大类');
            return false;
        }
        if($.trim($('#<%=txtProductName.ClientID %>').val()).length < 2 
        && $.trim($('#<%=txtMajorFunction.ClientID %>').val()).length < 2 
        && $('#<%=ddlFirstCategory.ClientID%>').val() == "-1")
        {
            alert("请至少输入2个字符进行查询");
            if($('#<%=txtProductName.ClientID %>').val().length < 2)
            {
                $("#<%=txtProductName.ClientID %>").focus();
                return false;
            }
            if($("#<%=txtMajorFunction.ClientID %>").val().length < 2)
            {
                $("#<%=txtMajorFunction.ClientID %>").focus();
                return false;
            }
        }
        else
        {
            var url = "../BreedManage/NewSelBreed.aspx?productname="+$.trim($('#<%=txtProductName.ClientID %>').val())
            +"&majorfunction=" + $.trim($('#<%=txtMajorFunction.ClientID %>').val())
            +"&firstcategory=" + $('#<%= ddlFirstCategory.ClientID %>').val()
            +"&functionsys=" + $('#<%= ddlFunctionSys.ClientID %>').val()
            +"&secondcategory=" +$('#<%= ddlSecondCategory.ClientID %>').val()
            +"&dosageform=" + $('#<%= ddlDosageform.ClientID %>').val()
            +"&otc="+ $('#<%= ddlOTC.ClientID %>').val()
            +"&exclusiveproduct=" +$('#<%=ddlExclusiveProduct.ClientID%>').val()
            +"&insuranceproduct=" + $('#<%=ddlInsuranceProduct.ClientID%>').val()
            +"&protectproduct=" + $('#<%=ddlProtectProduct.ClientID%>').val()
            +"&primaryproduct=" + $('#<%=ddlPrimaryProduct.ClientID%>').val()
            +"&page="+"<%=page %>";
            location.href=url;
        }
     }
     
     var LookScript = function(productname,majorfunction,firstcategory,functionsys,secondcategory,dosageform,otc,exclusiveproduct,insuranceproduct,protectproduct,primaryproduct,drugname,page)
     {
        var url = "../BreedManage/SelBreed.aspx?productname="+productname
            +"&majorfunction=" + majorfunction
            +"&firstcategory=" + firstcategory
            +"&functionsys=" + functionsys
            +"&secondcategory=" +secondcategory
            +"&dosageform=" + dosageform
            +"&otc="+ otc
            +"&exclusiveproduct=" +exclusiveproduct
            +"&insuranceproduct=" + insuranceproduct
            +"&protectproduct=" + protectproduct
            +"&primaryproduct=" + primaryproduct
            +"&drugname="+drugname
            +"&page="+page;
            location.href=url;
     }
     $(function(){
        $("#SearchPanel input[type='text']").bind('keydown',function(){
            Go();
        });
        $("#SearchPanel select").keydown(function(){
            Go();
        });
        $("#SearchPanel select:lt(2)").change(function(){
            if($(this).val() != "-1"){
                //getXmlJson($(this).val(),$(this).next("select"));//通过调用WebService
                GetXmlJsonToAshx($(this).val(),$(this).next("select"));//通过调用一般处理程序
            }
            else
            {
                if(this.id == '<%=ddlFirstCategory.ClientID %>'){
                  $(this).next("select").val('-1').next("select").val('-1');
                  $(this).next("select").next("select").get(0).options.length = 1;
               }else{
                  $(this).next("select").val('-1');
               }
               $(this).next("select").get(0).options.length = 1;               
            }
        });
        if("<%=FirstCategory %>" != "")
        {
            $("#<%=ddlFirstCategory.ClientID %>").change();
        }
        
     });
     
     //Jquery ajax调用WebService
     var getXmlJson = function(mess,selectName){
           $.ajax({
               type: "post",
               contentType:"application/json",
               url: "../TestServices.asmx/GetDrugsCategory",
               data: "{xmlname:'"+mess+"'}",
               datatype:"json", 
               success: function(data) { 
                   var options = selectName.get(0).options;
                   options.length = 1;
                   if(selectName.get(0).id == '<%=ddlFunctionSys.ClientID %>')
                      selectName.next("select").get(0).options.length = 1;
                   var json = eval(data);
                   if(!json)
                      return;  
                   $.each(json,function(i,n){
                      options.add(new Option(n.name,n.name));
                   });
                   if($('#<%=ddlFunctionSys.ClientID %>').val() == "-1" && "<%=FunctionSys %>" != ""){                  
                      $('#<%=ddlFunctionSys.ClientID %>').val('<%=FunctionSys %>'); 
                      $('#<%=ddlFunctionSys.ClientID %>').change(); 
                   }
                   if($('#<%=ddlSecondCategory.ClientID %>').val() == "-1" && "<%=SecondCategory %>" != ""){
                       $('#<%=ddlSecondCategory.ClientID %>').val('<%=SecondCategory %>'); 
                       $('#<%=ddlSecondCategory.ClientID %>').change(); 
                   }
              },
              error: function(x, e) {
                   alert("失败:"+x.responseText);
              }  
            });
        }
     //Jquery ajax调用ashx
    var GetXmlJsonToAshx = function(mess,selectName)
    {
        $.ajax({
            type:"post",
            url: "../HandlerDrugsCategory.ashx?action=test",
            contentType:"application/x-www-form-urlencoded;charset=UTF-8",     
            data: "xmlname="+mess,//提交表单,相当于HandlerDrugsCategory.ashx?xmlname=XXX
            //json格式接收数据
            datatype:"json",             
            success:function(data) {
                   // 请求成功后回调函数 参数:服务器返回数据,数据格式.
                   var options = selectName.get(0).options;
                   options.length = 1;
                   if(selectName.get(0).id == '<%=ddlFunctionSys.ClientID %>')
                      selectName.next("select").get(0).options.length = 1;
                   var json = eval(data);
                   if(!json)
                      return;  
                   $.each(json,function(i,n){
                      options.add(new Option(n.name,n.name));
                   });
                   if($('#<%=ddlFunctionSys.ClientID %>').val() == "-1" && "<%=FunctionSys %>" != ""){                  
                      $('#<%=ddlFunctionSys.ClientID %>').val('<%=FunctionSys %>'); 
                      $('#<%=ddlFunctionSys.ClientID %>').change(); 
                   }
                   if($('#<%=ddlSecondCategory.ClientID %>').val() == "-1" && "<%=SecondCategory %>" != ""){
                       $('#<%=ddlSecondCategory.ClientID %>').val('<%=SecondCategory %>'); 
                       $('#<%=ddlSecondCategory.ClientID %>').change(); 
                   }
              },
              error: function(x, e) {
                   alert("失败:"+x.responseText);
              }  
        });
    }
</script>
</asp:Content>

ashx:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Web.SessionState;
using System.Text;

namespace WebApp.SaleApp
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class HandlerDrugsCategory : IHttpHandler, IRequiresSessionState 
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            //context.Response.Charset = "gb2312";//utf-8
            string action = context.Request.Params["action"].ToString();
            if (action == "test")
            {
                //string strJson = GetDrugsCategory(HttpContext.Current.Server.UrlDecode(context.Request.Params["xmlname"].ToString()));
                string strJson = GetDrugsCategory(HttpUtility.UrlDecode(context.Request.Params["xmlname"].ToString(), Encoding.GetEncoding("utf-8")));
                context.Response.Write(strJson);
                context.Response.End();
            }
        }
        /// <summary>
        /// 业务员查询药品分类
        /// </summary>
        /// <param name="xmlname">查询节点名称</param>
        /// <returns></returns>
        public string GetDrugsCategory(string xmlname)
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(HttpContext.Current.Server.MapPath("./XmlData/YwHyDrugCategory.xml"));
            XmlNode xnode = xd.DocumentElement;
            XmlNode node = null;
            GetXMLNode(xnode, ref node,xmlname);
            return GetXmlJson(node);
        }

        /// <summary>
        /// 将XML解析成数据格式为Json的数据供JS使用
        /// 返回json数据
        /// </summary>
        /// <param name="node">XML节点</param>
        /// <returns></returns>
        private string GetXmlJson(XmlNode node)
        {
            try
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                if (node != null)
                {
                    sb.Append("[");
                    foreach (XmlNode xnode in node.ChildNodes)
                    {
                        sb.Append("{\"name\":\"" + xnode.Attributes["name"].Value + "\"},");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    sb.Append("]");
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 递归调用解析XML
        /// </summary>
        /// <param name="xnode">XML根节点</param>
        /// <param name="node">返回XML节点</param>
        /// <param name="message">查询XML节点名称</param>
        private void GetXMLNode(XmlNode xnode, ref XmlNode node, string message)
        {
            try
            {
                if (xnode.HasChildNodes)
                {
                    foreach (XmlNode var in xnode.ChildNodes)
                    {
                        string name = var.Attributes["name"].Value;
                        if (name == message)
                        {
                            node = var;
                            return;
                        }
                        GetXMLNode(var, ref node, message);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

asmx:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;

using System.Web.Script.Services;
using System.Xml;

namespace WebApp.SaleApp
{
    /// <summary>
    /// TestServices 的摘要说明
    /// 业务员第二种查询方式中药片分类级联下拉三级列表
    /// CnHney.wl
    /// 2011-03-28
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [ScriptService]
    public class TestServices : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        /// <summary>
        /// 业务员查询药品分类
        /// </summary>
        /// <param name="xmlname">查询节点名称</param>
        /// <returns></returns>
        [WebMethod(EnableSession=true)]
        [ScriptMethod]
        public string GetDrugsCategory(string xmlname)
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(Server.MapPath("./XmlData/YwHyDrugCategory.xml"));
            XmlNode xnode = xd.DocumentElement;
            XmlNode node = null;
            GetXMLNode(xnode, ref node, xmlname);
            return GetXmlJson(node);
        }

        /// <summary>
        /// 将XML解析成数据格式为Json的数据供JS使用
        /// 返回json数据
        /// </summary>
        /// <param name="node">XML节点</param>
        /// <returns></returns>
        private string GetXmlJson(XmlNode node)
        {
            try 
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                if (node != null)
                {
                    sb.Append("[");
                    foreach (XmlNode xnode in node.ChildNodes)
                    {
                        sb.Append("{'name':'"+xnode.Attributes["name"].Value +"'},");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    sb.Append("]");
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 递归调用解析XML
        /// </summary>
        /// <param name="xnode">XML根节点</param>
        /// <param name="node">返回XML节点</param>
        /// <param name="message">查询XML节点名称</param>
        private void GetXMLNode(XmlNode xnode, ref XmlNode node, string message)
        {
            try
            {
                if(xnode.HasChildNodes)
                {
                    foreach (XmlNode var in xnode.ChildNodes)
                    {
                        string name = var.Attributes["name"].Value;
                        if (name == message)
                        {
                            node = var;
                            return;
                        }
                        GetXMLNode(var, ref node, message);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}

仅供参考,欢迎拍砖!

原文地址:https://www.cnblogs.com/Leo_wl/p/2001013.html