這節主要內容是通過AJAX調用頁面后台代碼方法實現下拉框二級聯動效果,實現步驟如下:
1.創建文件Recipe24.aspx,實現后台代碼如下:
// 引入命名空間
using System.Web.Services;
// 實現下拉框二級聯動AJAX請求加載數據方法
[WebMethod()]
public static ArrayList GetSubList(string sBuyID)
{
ArrayList subList = new ArrayList();
if (sBuyID == "1")
{
subList.Add(new ListItem("文藝", "1"));
subList.Add(new ListItem("少兒", "2"));
subList.Add(new ListItem("人文社科", "3"));
subList.Add(new ListItem("科技", "4"));
}
else if (sBuyID == "2")
{
subList.Add(new ListItem("手機通訊", "1"));
subList.Add(new ListItem("手機配件", "2"));
subList.Add(new ListItem("攝影攝像", "3"));
subList.Add(new ListItem("數碼配件", "4"));
}
return subList;
}
2.實現頁面代碼(HTML部分)如下:
<body>
<form id="form1" runat="server">
<div align="center">
<fieldset style="width: 400px; height: 150px;">
<table border="0" cellpadding="10" cellspacing="10">
<tr>
<td>
<asp:DropDownList ID="buyList" runat="server" Width="120px">
<asp:ListItem Value="0" Text=" --- 請選擇 --- "></asp:ListItem>
<asp:ListItem Value="1" Text="圖書"></asp:ListItem>
<asp:ListItem Value="2" Text="手機數碼"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="subList" runat="server" Width="120px">
<asp:ListItem Value="0" Text=" --- 請選擇 --- "></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</fieldset>
</div>
</form>
</body>
3.實現腳本代碼如下:
<script type="text/javascript">
$(function () {
$("#buyList").bind("keyup change", function (e) {
e.preventDefault();
// 首先初始化
$("#subList").empty().append($("<option></option>").val("0").html(" --- 請選擇 --- "));
if ($(this).val() != "0") {
sendData($(this).val());
}
});
function sendData(sBuyID) {
var loc = window.location.href;
$.ajax({
type: "POST",
url: loc + "/GetSubList", // 調動后台頁面方法
data: '{"sBuyID":"' + sBuyID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// msg.d是數組,由后台數組ArrayList返回,因此可以遍歷每個元素
$.each(msg.d, function () {
// this.Value和this.Text是后台返回數組ArrayList類型包含元素ListItem類型的屬性
$("#subList").append($("<option></option").val(this.Value).html(this.Text));
});
},
error: function () {
alert("ajax請求發生錯誤");
}
});
}
});
</script>
4.下拉框二級聯動效果圖:
5.分析XmlHttpRequest對象,可看到請求響應的數據msg.d的結構如下(通過下圖就知道msg.d的每個元素為什么會有Text和Value屬性了):
今天發現一個問題,就是以上代碼如果在VS2005建立的項目里面運行,AJAX會報JSON對象錯誤,但在VS2010項目里面運行正常,一直沒找到原因,哪位高手如果知道其原因,請告知,謝謝。