使用ajax概念在下拉列表中发布
本文关键字:下拉列表 ajax 使用 | 更新日期: 2023-09-27 18:24:05
在下面的代码中,我正在使用ajax概念处理下拉列表。我的问题是,我可以返回逗号分隔的值,在回调方法中,它的msg参数值是对象。请帮我解决这个问题。第二个下拉值没有绑定。
$(document).ready(OnReady);
function OnReady() {
//Handle the change event for the drop down list
$("#ddlLocation").change(onChange);
}
function onChange() {
//create the ajax request
$.ajax
(
{
type: "POST", //HTTP method
url: "NewIndent.aspx/OnContinentChange", //page/method name
data: "{'continentName':'" + $("#<%=ddlLocation.ClientID%>").val() + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
success: callback,
error: onError
}
);
}
//Handle the callback on success
function callback(msg) {
alert(msg);//it shows object object
var countries = msg.split(';');
var length = countries.length;
document.getElementById('<%=ddlProduct.ClientID %>').options.length = 0;
var dropDown = document.getElementById('<%=ddlProduct.ClientID %>');
for (var i = 0; i < length - 1; ++i) {
var option = document.createElement("option");
option.text = countries[i];
option.value = countries[i];
dropDown.options.add(option);
}
}
//Handle the callback on error
function onError() {
alert('something went wrong');
}
[System.Web.Services.WebMethod]
public static string OnContinentChange(int continentName)
{
MastersClient objProductName = new MastersClient();
DataSet dsProduct = objProductName.GetLocationProductMap(continentName);
DataTable firstTable = dsProduct.Tables[1];
string result = string.Empty;
foreach (DataRow r in firstTable.Rows)
{
result += r["ProductName"].ToString() + ";";
}
return result;//return all the values in comma separated
}
<asp:DropDownList ID="ddlLocation" runat="server" style="width:40%;" EnableViewState="true" onchange="onChange()" />
<asp:DropDownList ID="ddlProduct" runat="server" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged" AutoPostBack="true" Style="width: 100%; height:23px" ></asp:DropDownList>
您将得到一个Json object
作为返回,它是key value pair
的组合因此检索success
上的数据作为
success: function (object) {
$.each(object, function (key, val) {
alert(key);alert(val);
})
}
function callback(msg) {
alert(msg);//it shows object object
var countries = msg.split(';');
var length = countries.length;
document.getElementById('<%=ddlProduct.ClientID %>').options.length = 0;
var dropDown = document.getElementById('<%=ddlProduct.ClientID %>');
$.each(msg, function (key, val) {
var option = document.createElement("option");
option.textContent = key;
option.value = key;
dropDown .appendChild(option);
})
}
//Handle the callback on error
function onError() {
alert('something went wrong');
}
使用此
dropDown.appendChild(option);
而不是
dropDown.options.add(option);