jQuery+ajax城市联动
分享一下自己最近写的城市联动。技术使用ajax+jQuery实现。
首先请看前台的javascript代码。
以下是连个实现异步加载的方法。
<script type="text/javascript"> $(function () { loadProvince(); loadCity(); }); function loadProvince() { $.ajax({ type: "get", url: "province_city.ashx", data: "pid=-1", async: false,//同步 success: function (json) { var jsons = eval(json); var province = document.getElementById("province"); for (var i = 0; i < jsons.length; i++) { var p = jsons[i]; if (p.Pid == -1) { var option = document.createElement("option"); option.value = p.Id; option.innerHTML = p.Name; province.appendChild(option); } } } }); }; //加载市 function loadCity() { city.innerHTML = "";//清空控件内容 var pid = document.getElementById("province").value;//获得省的pid $.ajax({ type: "get", url: "province_city.ashx", data: "pid=" + pid, success: function (json) { var jsons = eval(json); var city = document.getElementById("city"); for (var i = 0; i < jsons.length; i++) { var c = jsons[i]; var option = document.createElement("option"); option.value = c.Id; option.innerHTML = c.Name; city.appendChild(option); } } }); }; </script>
在使用前请引用jQuery。
后台的代码用的ashx.
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string s= context.Request.QueryString["pid"]; int pid; if (int.TryParse(s,out pid)) { string json = GetDataByPid(pid); context.Response.Write(json); } } private string GetDataByPid(int pid) { List<Data> list = GetAllDatas(); List<Data> datas = new List<Data>(); foreach (Data item in list) { if (item.Pid == pid) { datas.Add(item); } } //把对象转换成json格式的字符串 JavaScriptSerializer jss = new JavaScriptSerializer(); string json = jss.Serialize(datas); return json; } private List<Data> GetAllDatas() { List<Data> list = new List<Data>(); list.Add(new Data() { Id = 1, Name = "河南省", Pid = -1 }); list.Add(new Data() { Id = 2, Name = "台湾省", Pid = -1 }); list.Add(new Data() { Id = 3, Name = "日本省", Pid = -1 }); list.Add(new Data() { Id = 4, Name = "郑州市", Pid = 1 }); list.Add(new Data() { Id = 5, Name = "济源市", Pid = 1 }); list.Add(new Data() { Id = 6, Name = "焦作市", Pid = 1 }); list.Add(new Data() { Id = 7, Name = "高雄市", Pid = 2 }); list.Add(new Data() { Id = 8, Name = "台北", Pid = 2 }); list.Add(new Data() { Id = 9, Name = "台中", Pid = 2 }); list.Add(new Data() { Id = 10, Name = "东京", Pid = 3 }); list.Add(new Data() { Id = 11, Name = "冲绳", Pid = 3 }); list.Add(new Data() { Id = 12, Name = "大阪", Pid = 3 }); return list; }