ajax實現三級聯動菜單代碼

來源:互聯網
上載者:User

類似的三級綁定,但在修改資訊的時候,綁定然後再提交,下拉框的值總會消失,或者就是回傳以後,下拉框的值也會消失,這兩天又遇到同樣的問題,所以下決心把這個徹底搞定。

本執行個體用的是jquery+ashx實現。


第一種情況,只有提交的情況

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Area.asp教程x.cs" Inherits="Area" %>

<!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 runat="server">
    <title>無標題頁</title>
    <script type="text/網頁特效" src="js/jquery.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function(){
          doChange(null,"province","0");
       });
       function doChange(id,sub_id,id_value)
       {
          $("#"+sub_id).empty();
          var p_id=id_value;
          if(id!=null)
          {
             p_id=$("#" + id).val();
          }
          var options="<option value="">請選擇</option>";
          if(p_id!="")
          {
              $.getJSON("GetArea.ashx",{pid:p_id},function(data){
                 $.each(data.items,function(i,item){
                    options += "<option value="" + item.value + "">" + item.text + "</option>";
                 });
                 $("#" + sub_id).append(options);
              });
          }
          else
          {
             $("#" + sub_id).append(options);
          }
       }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <select name="province" id="province" onchange="doChange('province','city','0','')"></select>省
    <select name="city" id="city" onchange="doChange('city','area','0','')"></select>市
    <select name="area" id="area"></select>縣
    </div>
    </form>
</body>
</html>

三個select分別用於顯示省,市,縣

以下是GetArea.ashx代碼

<%@ WebHandler Language="C#" Class="GetArea" %>

using System;
using System.Web;
using System.Data;
using GeodonHelper;

public class GetArea : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        string startValue = "{"items":[";
        string endValue = "]}";
        if (context.Request.QueryString["pid"] == null || !ValidateHelper.IsInteger(context.Request.QueryString["pid"].ToString()))
        {
            context.Response.Write(startValue + "{value:"",text:"參數錯誤"}" + endValue);
            context.Response.End();
        }
        else
        {
            int pid = int.Parse(context.Request.QueryString["pid"].ToString());

            string middleValue = "";
            //DBHelper是我自己寫的資料庫教程操作類庫,目前支援MSSQL MySql,Access,SQlite,此處的代碼可以換成你自己的資料庫作業碼。

            DBHelper sh = DBHelper.CreateInstance();

            string sql = "select Id,AreaName from Area where ParentId=@pid";
            sh.Params.Add("@pid", pid);
            DataTable tb = sh.ExecuteDataTable(sql);
            int count = tb.Rows.Count;
            if (count == 0)
            {
                context.Response.Write(startValue + "{value:"",text:"沒有資料"}" + endValue);
                context.Response.End();
            }
            else
            {
                for (int i = 0; i < count; i++)
                {
                    middleValue += ",{value:"" + tb.Rows[i]["Id"].ToString().Trim() + "",text:"" + tb.Rows[i]["AreaName"].ToString().Trim() + ""}";
                }

                middleValue = middleValue.Substring(1);
                context.Response.Write(startValue + middleValue + endValue);
                context.Response.End();
            }
        }
    }
 
    public bool IsReusable {
        get {
            return true;
        }
    }

}

 

提交資料的時候用Request["province"],Request["city"],Request["area"]

第二種情況:修改資訊先從資料庫擷取省市縣編號,然後綁定三個select,然後再提交資料.

aspx頁面

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

<!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 runat="server">
    <title>無標題頁</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function(){
          GetProvince();
       });
       function GetProvince()
       {
          var province=$("#province");
          province.empty();
          var options="<option value="">請選擇</option>";
          $.getJSON("GetArea.ashx",{pid:"0"},function(data){
             $.each(data.items,function(i,item){
                options += "<option value="" + item.value + "">" + item.text + "</option>";
             });
             province.append(options);
             province.val("<%=province %>");
             GetCity();
          });
       }
       function GetCity()
       {
          var city=$("#city");
          city.empty();
          var p_id=$("#province").val();
          var options="<option value="">請選擇</option>";
          if(p_id!="")
          {
              $.getJSON("GetArea.ashx",{pid:p_id},function(data){
                 $.each(data.items,function(i,item){
                    options += "<option value="" + item.value + "">" + item.text + "</option>";
                 });
                 city.append(options);
                 city.val("<%=city %>");
                 GetArea();
              });
          }
          else
          {
             city.append(options);
             GetArea();
          }
         
       }
       function GetArea()
       {
          var area=$("#area");
          area.empty();
          var p_id=$("#city").val();
          var options="<option value="">請選擇</option>";
          if(p_id!="" && p_id!=null)
          {
              $.getJSON("GetArea.ashx",{pid:p_id},function(data){
                 $.each(data.items,function(i,item){
                    options += "<option value="" + item.value + "">" + item.text + "</option>";
                 });
                 area.append(options);
                 area.val("<%=area %>");
              });
          }
          else
          {
             area.append(options);
          }
       }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <select name="province" id="province" onchange="GetCity()"></select>省
    <select name="city" id="city" onchange="GetArea()"></select>市
    <select name="area" id="area"></select>縣
    </div>
    <asp:Button ID="btn_submit" runat="server" Text="提交表單"
        onclick="btn_submit_Click" /> http://www.111cn.net
    <br />
    <asp:Label ID="lbl_msg" runat="server"></asp:Label>
    </form>
</body>
</html>

 

因為要為每個select賦值,而這個賦值又只能在ajax載入成功之後進行,所以我採取的辦法是寫三個方法,分別用於載入省,市,縣

下面是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.Xml.Linq;
using GeodonHelper;

public partial class Edit : System.Web.UI.Page
{
    public string province = "", city = "", area = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
        {
            province = "97";
            city = "279";
            area = "1469";
        }
    }
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        lbl_msg.Text = Request["province"] + "&" + Request["city"] + "&" + Request["area"];
    }
}

 

ajax載入資料用的還是GetArea.ashx。 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.