這節主要內容是通過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項目里面運行正常,一直沒找到原因,哪位高手如果知道其原因,請告知,謝謝。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
