前台
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" onchange="change(this)">
</asp:DropDownList>
<select id="select_city">
</select>
</div>
</form>
<script type="text/javascript">
function change(obj) {
var province_ID = $(obj).children("option:selected").attr("Value");
$.ajax({
url: '/Services/getCity.ashx',
data: { "province_ID": $(obj).children("option:selected").attr("Value") },
type: 'POST',
dataType: 'text',
success: function(data) {
var json = $.parseJSON(data);
$select_city = $("#select_city");
$select_city.children().remove();
$.each(json, function(i, item) {
$select_city.append("<option value='" + item.City_ID + "'>" + item.City_Name + "</option>");
});
},
error: function() {
alert('error !');
}
});
}
后台
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string province_ID = context.Request.Params["province_ID"];
DataTable dt = SingleTon<SqlDataAccess>.instance.getTable("select t.City_ID,t.City_Name from City t where t.Province_ID='"+province_ID+"'");
string json = JsonHelper.getJson(dt, "City_ID", "City_Name");
context.Response.Write(json);
} public static string getJson(DataTable dt, params string[] pars)
{
string json = string.Empty;
if (dt == null)
return json;
json += "[";
foreach (DataRow dr in dt.Rows)
{
string temp = "{";
foreach (string par in pars)
{
temp += string.Format("\"{0}\":\"{1}\",", par, dr[par]);
}
temp = temp.Remove(temp.Length - 1, 1);
temp += "},";
json += temp;
}
json = json.Remove(json.Length - 1, 1);
json += "]";
return json;
}
本文介绍了一种使用Ajax和JavaScript实现省市联动下拉框的方法。通过选择省份时触发Ajax请求,动态更新城市下拉框的内容。具体实现包括前端HTML、ASP.NET元素以及后端处理逻辑。
4226

被折叠的 条评论
为什么被折叠?



