JQuery+ajax 三级联动

寻技术 JQuery / JS脚本 2023年07月30日 105

html中代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="js/jquery-1.7.2.min.js"></script>
</head>
<body>
    <select id="sel1">
        <option>加载中...</option>
    </select>
    <select id="sel2">
        <option>加载中...</option>
    </select>
    <select id="sel3">
        <option>加载中...</option>
    </select>

    <script type="text/javascript">
        a($("#sel1"), "", "");

        $("#sel1").change(function () {
            a($("#sel2"), $("#sel1").val(), "");
        });

        $("#sel2").change(function () {
            a($("#sel3"), $("#sel2").val(), "");
        });

        function a(sel, code, count) {
            $.ajax({
                url: "ashxs/china.ashx",
                data: { "code": code },
                type: "post",
                dataType: "json",
                success: function (data) {
                    sel.empty();
                    for (i in data) {
                        sel.get().add(new Option(data[i].name, data[i].code));
                    }
                    if (count == "") {
                        a($("#sel2"), $("#sel1").val(), "");
                    }
                    if (count == "") {
                        a($("#sel3"), $("#sel2").val(), "");
                    }
                }
            });//ajax
        }

    </script>
</body>
</html>

一般处理程序中的代码:

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

using System;
using System.Web;
using System.Linq;
using System.Data.Linq;
using System.Collections;
using System.Collections.Generic;

public class china : IHttpHandler
{
    DataClassesDataContext con = new DataClassesDataContext();
    public void ProcessRequest(HttpContext context)
    {
        string end = "[";
        int count = ;
        string code = context.Request["code"];
        List<ChinaStates> list = con.ChinaStates.Where(r => r.ParentAreaCode == code).ToList();
        if (list.Count > )
        {
            foreach (ChinaStates c in list)
            {
                if (count <= )
                {
                    end += "{\"name\":\"" + c.AreaName + "\",\"code\":\"" + c.AreaCode + "\"}";
                }
                else
                {
                    end += ",{\"name\":\"" + c.AreaName + "\",\"code\":\"" + c.AreaCode + "\"}";
                }
                count++;
            }
        }
        end += "]";
        context.Response.Write(end);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

关闭

用微信“扫一扫”