在网站注册的页面上经常要选择注册地点,如果改变省的名称就能出现对应的市级的名称,将为用户带来很大的方便,虽然用.NET的服务端时间实现很容易,不过选一下刷新页面的操作,用户体验实在不怎么样,现在给大家送上AJAX实现的三级联动
代码有点多,但是实际的项目过程中,我们必须这么做
应要求,先给大家一个代码下载地址.DropDownList控件实现省市联动(AJAX实现) 。放心,偶得资源不要积分
首先在页面上初始化省的数据,添加onchange的js事件。。在用户改变地区选择的时候,调用JS函数(通过AJAX)调用后台C#代码,C#通过查询数据库,返回数据,并生成HTML,传给客户端,客户端在拿到HTML,放到相应的位置,即可。
jquery的ajax是异步的,这样不会阻塞浏览器,也不用刷新页面。
减少了网络开销也降低了服务器压力,最重要的是用户体验更好了。
首先,建立数据库,SQL如下:
create database zone
go
use zone
go
create table zone
(
id int primary key identity(1,1),
name varchar(30),
iid int
)
/*iid int references zone(id)*/
然后,建立一个WebApplication的工程。
引入jquery.js。。新建3个文件Service.cs(数据库访问)、LinkageAjax.ashx(响应AJAX请求)、Default.aspx(联动页面)。如下图所示:
首先,编写Service.cs(数据库访问)代码:
using System.Data;
using System.Data.SqlClient;
namespace Test_Ajax.Linkage
{
public class Service
{
private const string conStr = "server = .;database = zone;uid = sa; pwd = 3717";
public DataTable GetZoneInfo(int fatherID)
{
using (SqlConnection con = new SqlConnection(conStr))
{
string sql = "select * from zone(nolock) where iid = " + fatherID;
SqlDataAdapter adp = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
adp.Fill(dt);
con.Close();
return dt;
}
}
}
}
然后是Default.aspx(联动页面)代码。
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test_Ajax.Linkage.Default" %>
<!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 src="../JS/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
function GetZoneInfo(zoneID, level) {
$.ajax({
type: "POST",
url: "LinkageAjax.ashx?type=GetZoneInfo" + "&zoneID=" + zoneID + "&level=" + level + "&random=" + Math.random(),
data: "",
beforeSend: function() { },
success: function(msg) {
switch (level) {
case 1:
$("#span_City").html(msg);
break;
case 2:
$("#span_County").html(msg);
break;
default:
break;
}
},
error: function() { alert("网络繁忙,请稍后再试。"); },
complete: function() { }
});
}
function ChangeSlect(zoneID, name) {
if (zoneID == "0") return;
switch (name) {
case "<%=Drop_Province.ClientID%>":
GetZoneInfo(zoneID, 1);
break;
case "Drop_City":
GetZoneInfo(zoneID, 2);
break;
default:
break;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="span_Province">
<asp:DropDownList ID="Drop_Province" runat="server"
οnchange="ChangeSlect(this.options[this.selectedIndex].value,this.name)"
ondatabound="Drop_Province_DataBound">
</asp:DropDownList>省
</span>
<span id="span_City"></span>
<span id="span_County"></span>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI.WebControls;
using System.Data;
namespace Test_Ajax.Linkage
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Service ser = new Service();
DataTable dt = ser.GetZoneInfo(0);
Drop_Province.DataSource = dt;
Drop_Province.DataTextField = "name";
Drop_Province.DataValueField = "id";
Drop_Province.DataBind();
}
}
protected void Drop_Province_DataBound(object sender, EventArgs e)
{
Drop_Province.Items.Insert(0,new ListItem("未选择", "0"));
Drop_Province.SelectedValue = "0";
}
}
}
最后是LinkageAjax.ashx(响应AJAX请求)的代码:
using System;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Text;
namespace Test_Ajax.Linkage
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class LinkageAjax : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (!string.IsNullOrEmpty(context.Request.QueryString["type"]))
{
switch (context.Request.QueryString["type"])
{
case "GetZoneInfo":
GetZoneInfo(context);
break;
default:
break;
}
}
}
public void GetZoneInfo(HttpContext context)
{
if (!string.IsNullOrEmpty(context.Request.QueryString["zoneID"])
&& !string.IsNullOrEmpty(context.Request.QueryString["level"]))
{
string controlName = "";
switch (context.Request.QueryString["level"])
{
case"1":
controlName = "Drop_City";
break;
case"2":
controlName = "Drop_County";
break;
default:
return;
}
Service ser = new Service();
DataTable dt = ser.GetZoneInfo(int.Parse(context.Request.QueryString["zoneID"]));
StringBuilder sb = new StringBuilder();
sb.Append(String.Format("<select name=\"{0}\" id=\"{1}\" οnchange=\"ChangeSlect(this.options[this.selectedIndex].value,this.name)\">", controlName, controlName));
sb.Append("<option value=\"0\">未选择</option>");
foreach (DataRow row in dt.Rows)
{
sb.Append("<option value=\"");
sb.Append(row["id"].ToString());
sb.Append("\">");
sb.Append(row["name"].ToString());
sb.Append("</option>");
}
sb.Append("</select>");
context.Response.Write(sb.ToString());
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
最后,贴给大家一点数据的INSERT语句:
insert into zone (name,iid)
values('四川',0)
insert into zone (name,iid)
values('绵阳',1)
insert into zone (name,iid)
values('乐山',1)
insert into zone (name,iid)
values('云南',0)
insert into zone (name,iid)
values('大理',4)
insert into zone (name,iid)
values('昆明',4)
insert into zone (name,iid)
values('上海',0)
insert into zone (name,iid)
values('夹江',3)
insert into zone (name,iid)
values('涪城',2)
insert into zone (name,iid)
values('广州',0)
insert into zone (name,iid)
values('深圳',10)
insert into zone (name,iid)
values('广东',10)
insert into zone (name,iid)
values('江苏',0)
insert into zone (name,iid)
values('杭州',13)
insert into zone (name,iid)
values('无锡',13)
insert into zone (name,iid)
values('南京',13)
insert into zone (name,iid)
values('常州',13)