本文分享一個基於 Ajax 的省市級聯菜單實例,包含前端 HTML 頁面與後台數據接口兩個部分,代碼結構清晰,適合初學者動手實踐。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Ajax</title>
<script type="text/javascript">
function loadXMLDoc(txt) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var citys = xmlhttp.responseText.split(',');
document.getElementById("citys").length = 1;
for (i = 0; i < citys.length - 1; i++) {
document.getElementById("citys").add(new Option(citys[i], citys[i]));
}
}
}
xmlhttp.open("GET","ajax/getdata.aspx?pro="+txt, true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<select id="Select1" onchange="loadXMLDoc(this.value)">
<option>請選擇省份</option>
<option value="1">江蘇</option>
<option value="2">上海</option>
</select>
<select id="citys">
<option>請選擇城市</option>
</select>
<div id="myDiv"></div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ajax_getdata : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] js=new string[]{"南京", "蘇州", "常州" , "無錫" , "鎮江"};
string pro=Request.QueryString["pro"];
if (pro == "1")
{
string temp = "";
for (int i = 0; i < js.Length; i++)
{
temp = temp + js[i];
temp = temp + ",";
}
Response.Write(temp);
}
else
Response.Write("");
}
}
這個案例的核心思路是:當用戶選擇省份時,觸發 loadXMLDoc 函數向後台發起請求;後台根據傳入的省份參數返回對應的城市列表(以逗號分隔的字符串);前端收到響應後,用 split(',') 拆分字符串,再逐個添加到城市下拉框中。這樣就實現了省市的二級聯動效果。