• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
wjshan0808

Learn from yesterday, Live for today, For a better tomorrow.
 ————wjshan0808

博客园    首页    新随笔    联系   管理    订阅  订阅

省市联动初探AJAX操作数据

主要学习代码:

List.html

    <script type="text/javascript">
        function GetXhr() {
            return new XMLHttpRequest();
        }

        var getCities = function () {
            //alert(this.options[this.selectedIndex].value);
            //清空列表
            var cities = document.getElementById("sltCity");
            cities.options.length = 0;

            var id = this.options[this.selectedIndex].value;
            var xhr = GetXhr();
            xhr.open("post", "List.ashx", true);
            //post方式添加
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            //post方式永远不会使用浏览器的缓存
            //设置不使用浏览器缓存
            //xhr.setRequestHeader("If-Modified-Since", "0");

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var json = eval(xhr.response);
                    for (var i = 0; i < json.length; i++) {
                        var node=document.createElement("option");
                        node.innerHTML=json[i].Name;
                        cities.appendChild(node);
                    }
                }
            };
            xhr.send("pId=" + id);
        };
        function getProvinces() {
            //创建异步请求对象
            var xhr = GetXhr();
            // alert(xhr.readyState);//0
            //设置参数
            xhr.open("get", "List.ashx", true);

            // alert(xhr.readyState);//1
            xhr.onreadystatechange = function () {
                // alert(xhr.readyState);//4
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        // var s = [{ id: 1, name: 'value' }];
                        var cont = eval(xhr.responseText);
                        // alert(cont[0]);
                        //alert(cont.length);
                        var slt = document.getElementById("sltProvince");
                        for (var i = 0; i < cont.length; i++) {
                            slt.options[i] = new Option(cont[i].Name, cont[i].ID);
                        }
                    } else {
                        alert("服务器繁忙,请稍后在试。");
                    }
                }
            };
            //alert(xhr.readyState);//1
            //发送请求
            xhr.send();//post方式填写参数
            //alert(xhr.readyState);//1
        };
        window.onload = function () {
            getProvinces();
            document.getElementById("sltProvince").onchange = getCities;
        };
    </script>
</head>
<body>
    省:
    <select id="sltProvince">
    </select>
    &nbsp;市:<select id="sltCity">
    </select>
</body>

List.ashx:

<%@ WebHandler Language="C#" Class="List" %>

using System;
using System.Web;
using System.Collections.Generic;//List
//序列化命名空间
using System.Web.Script.Serialization; public class List : IHttpHandler { private Web.BLL.Transfer transfer = null; private List<Web.Model.PC> lpc = null; public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string id = context.Request.Form["pId"]; if (!string.IsNullOrEmpty(id)) { //第二种方式 //市 transfer = new Web.BLL.Transfer(); JavaScriptSerializer serializer = new JavaScriptSerializer(); lpc = transfer.GetProvincesOrCities(int.Parse(id)); //这样返回的json自动以属性为键。 //[{"Name":"白城市","Id":94}, string json = serializer.Serialize(lpc); context.Response.Write(json); } else { //第一种方式 //省 transfer = new Web.BLL.Transfer(); lpc = transfer.GetProvincesOrCities(0); System.Text.StringBuilder sb = new System.Text.StringBuilder(500); //拼接json字符串 sb.Append("["); foreach (Web.Model.PC item in lpc) { sb.Append("{ID:" + item.Id + ",Name:'" + item.Name + "'},"); } sb.Remove(sb.Length - 1, 1).Append("]"); context.Response.Write(sb.ToString()); } }

Web.BAL

    public class DataAction
    {
        private List<Web.Model.PC> lpc = null;
        private Web.Model.PC pc = null;
        public DataAction()
        {
            lpc = new List<Web.Model.PC>();
        }

        public List<Web.Model.PC> GetProvincesOrCities(int pId)
        {
            string sql = "select * from TblArea where AreaPId={0}";
            sql = string.Format(sql, pId);
            System.Data.DataTable dt = SqlHelper.ExecuteDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                foreach (System.Data.DataRow item in dt.Rows)
                {
                    pc = new Web.Model.PC(int.Parse(item[0].ToString()), item[1].ToString());
                    lpc.Add(pc);
                }
            }
            return lpc;
        }
    }

项目文件:http://pan.baidu.com/s/1hq9Ro7E


posted @ 2014-04-14 19:51  wjshan0808  阅读(247)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3