//樣本實現省市的二級無重新整理聯動選擇省名串連伺服器動態載入市名
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxCity.aspx.cs" Inherits="AjaxCity" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>根據省名擷取市名</title>
<script type="text/javascript">
var xmlHttp;
//建立XMLHttpRequest 對象
function createHttp()
{
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
xmlHttp = new XMLHttpRequest();
}
}
function showCity()
{
var url = "ShowCity.aspx?id="+document.getElementById("province").value;
//建立XMLHttpRequest對象
createHttp();
//指定伺服器響應函數
xmlHttp.onreadystatechange=showRes;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function showRes()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
addCity();
}
}
}
//根據省名添加市名
function addCity()
{
var citys = document.getElementById("city");
clearOptions(citys);
//擷取伺服器響應資料
var txt = xmlHttp.responseText;
var res=txt.split(",");
//添加新資料
for(var i=0;i<res.length;i++)
{
var opt = document.createElement("option");
opt.text=res[i];
opt.value=i;
citys.options.add(opt);
}
}
//清除記錄
function clearOptions(citys)
{
for( var i=citys.options.length;i>-1;i--)
{
citys.options.remove(i);
}
}
</script>
</head>
<body>
<select id="province" runat="server" style="width: 141px" onchange="showCity();">
<option selected="selected" value="1">湖北</option>
<option value="2">江蘇</option>
<option></option>
</select>
<select id="city" runat="server" style="width: 139px">
<option selected="selected"></option>
</select>
</body>
</html>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Text;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ShowCity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string id = Request.QueryString["id"].ToString();
this.ShowInfo(id);
}
}
/// <summary>
/// 根據省的編號查詢 市的名稱
/// </summary>
/// <param name="id"></param>
private void ShowInfo(string id)
{
SqlConnection con = new SqlConnection("Data source =(local);Initial Catalog=master;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("select * from city where pid=" + int.Parse(id), con);
con.Open();
SqlDataReader read = cmd.ExecuteReader();
StringBuilder str = new StringBuilder();
while (read.Read())
{
str.Append(read["cityName"].ToString() + ",");
}
Response.Write(str);
}
}