前台页面–省市联动
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
<script src="../../js/jquery.min.js"></script>
<script>
$(function () {
iniProvinceSelect();
})
function bindProSelectChangeEvent() {
$("#pro").change(function () {
//拿到省的id
var id = $(this).val();
$.get("AjaxProvinceCity.ashx", { ID: id }, function (data) {
$("#city").empty();
var json = $.parseJSON(data);
for (var key in json) {
var cId= json[key].id;
var cName = json[key].name;
$("#city").append("<option value='"+cId+"'>"+cName+"</option>");
}
});
})
};
function iniProvinceSelect() {
$.get("AjaxProvinceCity.ashx", "", function (data) {
$("#pro").html(data);
bindProSelectChangeEvent();
$("#pro").change();
});
}
</script>
</head>
<body>
<select id="pro"></select>
<select id="city"></select>
</body>
</html>
后台-由于嫌麻烦就没有连数据库,直接给了一个集合,如果连数据不扎实建议多写,但是工作时候基本上不写基础的数据库连接语句了,都是框架得不得得不得
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace Maticsoft.Web._2021_1_14.AjaxLogin
{
/// <summary>
/// AjaxProvinceCity 的摘要说明
/// </summary>
public class AjaxProvinceCity : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request["ID"]!=null) {
StringBuilder sb = new StringBuilder();
sb.Append("[");
List<model> Model = new List<AjaxProvinceCity.model> {
new model { id="1",name="哈尔滨市" },
new model { id="2",name="齐齐哈尔市" }
};
//foreach (var item in model)
//{
// sb.Append("{");
// sb.AppendFormat("\"CityId\":\"{0}\",\"CityName\":\"{1}\"", item.id, item.name);
// sb.Append("},");
//}
//string res = sb.ToString().TrimEnd(',') + "]";
var res = new JavaScriptSerializer().Serialize(Model);
context.Response.Write(res);
}
else
{
context.Response.ContentType = "text/plain";
StringBuilder sb = new StringBuilder();
List<model> model = new List<AjaxProvinceCity.model> {
new model { id="1",name="安徽" },
new model { id="2",name="北京" }
};
foreach (var item in model)
{
sb.AppendFormat("<option value='{0}'>{1}</option>", item.id, item.name);
}
context.Response.Write(sb.ToString());
}
}
public bool IsReusable
{
get
{
return false;
}
}
public class model
{
public string id { get; set; }
public string name { get; set; }
}
}
}