前端代码
function loadData(type,pid) {
$.getJSON('BookTypeList.ashx', { type: type, pid: pid }, function (data) {
//向服务期端传递参数,type ,标签名后面的变量值, pid: 主键ID
var typelist = $('#type' + type);
typelist.empty();
if (data.length <= 0) {
//如果没有查到数据就插入一个无数据的选项
typelist.append('<option value="-1">无子分类</option>')
}
else {
//遍历服务器端传回的json数据
$.each(data, function (index, item) {
//向select 标签中添加数据
typelist.append('<option value="' + item.TypeId + '">' + item.TypeTitle + '</option>');
});
//这里实现递归操作多级向select标签中添加数据
if (type < 3) {
loadData(type + 1, typelist.val());
}
}
});
}
调用该函数
$(function () {
//首先加载一级分类的数据
loadData(1, 0);
//加载二级分类
$('#type1').change(function () {
loadData(2, $(this).val());
});
//加载三级分类
$('#type2').change(function () {
loadData(3, $(this).val());
});
//如果有多级分类的话可以继续加载
});
<body>
<select id="type1" name="type1"></select>
<select id="type2" name="type2"></select>
<select id="type3" name="type3"></select>
</body>
后台服务器代码 用c#实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Script.Serialization;
namespace Maticsoft.Web.Admin
{
/// <summary>
/// BookTypeList1 的摘要说明
/// </summary>
public class BookTypeList1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
Maticsoft.BLL.BookType booktypeBll = new BLL.BookType();
int type = int.Parse(context.Request["type"]);
int pid = int.Parse(context.Request["pid"]);
string where = "";
if (type == 1)
{
where = " TypeParentId=0";
}
else
{
where = " TypeParentId=" + pid+" ";
}
DataTable dt = booktypeBll.GetList(where).Tables[0];
List<Maticsoft.Model.BookType> listType = new List<Model.BookType>();
foreach (DataRow dr in dt.Rows)
{
listType.Add(new Maticsoft.Model.BookType() {
TypeId=Convert.ToInt32(dr["TypeId"]),
TypeTitle=dr["TypeTitle"].ToString()
});
}
JavaScriptSerializer js = new JavaScriptSerializer();
context.Response.Write(js.Serialize(listType));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
数据表结构必须是省市联动,自链接表的类型才可以实现此功能