Jquery+Json+Handler文件结合应用实例

时间:2021-11-29 10:29:55

1、页面script代码-【model数据、字符串】

    <script type="text/javascript" charset="utf-8" src="Js/jquery-1.6.2.min.js"></script>
    <script type="text/javascript">
        //提交验证
        function ChekFrom()
        {
            var msg = "";
            //取值
            var UserName = $("#txtUserName").val();
            //验证
            if (UserName == "") {
                msg += "用户名为空!/r/n";

            } else {

                $.ajax({
                    type: "POST",
                    url: "/Controller/UserHandler.ashx",
                    data: { Action: "IsUserName", UserName: UserName },
                    cache: false, //设置时候从浏览器中读取 缓存  true 表示 是
                    datatype: "json",
                    async: false,
                    success: function (result) {
                        if (result.code == 1) {
                            msg += "该用户名已存在!/r/n";

                        }
                    }
                });
            }

            if (msg == "") {
                return true;
            } else {
                alert(msg);
                return false;
            }

        }

        //总计金额  可以写成js方法
        function BuyTotal() {

            var Total = $.ajax({
                type: "POST",
                dataType: text,//xml html script json
                url: "/Controller/UserHandler.ashx",
                data: { Action: "BuyTotal" },
                async: false
            }).responseText;

            return Total;
        }

    </script>

2、返回Model的handler代码

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

using System;
using System.Web;
using ECS.Utility;
using System.Collections.Generic;

//使用session的时候必须继承IRequiresSessionState接口:, System.Web.SessionState.IRequiresSessionState
public class UserHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        //全局默认返回信息
        string Json = JsonUtil.Serialize(new { code = 0, msg = "" });

        //取值
        string Action = context.Request.Form["Action"] == null ? "" : context.Request.Form["Action"].ToString().Trim();
        string UserName = context.Request.Form["UserName"] == null ? "" : context.Request.Form["UserName"].ToString().Trim();
        //判断
        if (!string.IsNullOrEmpty(Action))
        {
            //验证用户
            if (Action.Equals("IsUserName"))
            {
                //验证
                if (IsExistUser(UserName))
                {
                    Json = JsonUtil.Serialize(new { code = 1, msg = "用户名已存在!" });
                }
                else
                {
                    Json = JsonUtil.Serialize(new { code = 0, msg = "用户名可以注册!" });
                }

            }

            //计算金额
            if (Action.Equals("BuyTotal"))
            {
                //Json格式
                //Json = JsonUtil.Serialize(new { code = 1, msg = "成功", Total = 100 });
                //
                Json = "100";
            }
            else
            {   //Json格式
                //Json = JsonUtil.Serialize(new { code = 0, msg = "失败", Total = 0 });
                Json = "0";
            }

        }

        //最终返回信息
        context.Response.Write(Json);
    }

    /// <summary>
    /// 判断UserName是否存在
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <returns>返回true or false</returns>
    public bool IsExistUser(string userName)
    {

        List<LSY.Model.A_User> UserList = new LSY.BLL.A_User().GetList(null, "UserName='" + userName.Trim() + "'and Type=0", null);
        if (UserList.Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

3、页面script代码-【DataTable、List】

//查询城市
function getCity(CityVal) {
    var DDL_Province = $("#DDL_Province");
    var DDL_City = $("#DDL_City");
    DDL_City.empty();
    DDL_City.append("<option value=\"0\">市/区</option>");
    $.ajax(
    {
        type: "post",
        url: "/UserCart/Controller/CityAreas.ashx",
        data: { "type": "city", "provinceID": DDL_Province.val() },
        dataType: "json",
        async: false,
        success: function (msg) {

            for (var i = 0; i < msg.length; i++) {

                if (CityVal == msg[i].CityName) {
                    if (msg[i].IsCOD == 1) {
                        DDL_City.append("<option value=" + msg[i].CityID + " selected=\"selected\">" + msg[i].CityName + "*</option>");
                    } else {
                        DDL_City.append("<option value=" + msg[i].CityID + " selected=\"selected\">" + msg[i].CityName + "</option>");
                    }
                } else {
                    if (msg[i].IsCOD == 1) {
                        DDL_City.append("<option value=" + msg[i].CityID + " >" + msg[i].CityName + "*</option>");
                    } else {
                        DDL_City.append("<option value=" + msg[i].CityID + " >" + msg[i].CityName + "</option>");
                    }
                }
            }
            getArea('');
            GetAddreesSpan();
        }
    })
};

4、返回数据集Handler代码

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

using System;
using System.Web;
using System.Collections.Generic;

public class CityAreas : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        if (context.Request["type"] == "city")
        {
            context.Response.Write(select2(context.Request["provinceID"]));
        }
        else if (context.Request["type"] == "district")
        {
            context.Response.Write(select3(context.Request["cityID"]));
        }
    }

    public string select2(string id)
    {
        string str = string.Empty;
        if (!string.IsNullOrEmpty(id))
        {
            List<ECS.Model.A_CityAreas> list = new ECS.BLL.A_CityAreas().GetList(null, "deep=2 and ParentID=" + id, null);
            if (list != null && list.Count > 0)
            {

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("[");
                foreach (ECS.Model.A_CityAreas item in list)
                {
                    sb.Append("{");
                    sb.Append("\"CityID\":\"" + item.id + "\",\"CityName\":\"" + item.AreaName + "\",\"IsCOD\":\"" + item.IsCOD + "\"");
                    sb.Append("},");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("]");
                str = sb.ToString();
            }

        }
        return str;
    }

    public string select3(string id)
    {
        string str = string.Empty;
        if (!string.IsNullOrEmpty(id))
        {
            List<ECS.Model.A_CityAreas> list = new ECS.BLL.A_CityAreas().GetList(null, "deep=3 and ParentID=" + id, null);
            if (list != null && list.Count > 0)
            {

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("[");
                foreach (ECS.Model.A_CityAreas item in list)
                {
                    sb.Append("{");
                    sb.Append("\"DistrictID\":\"" + item.id + "\",\"DistrictName\":\"" + item.AreaName + "\",\"IsCOD\":\"" + item.IsCOD + "\"");
                    sb.Append("},");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("]");
                str = sb.ToString();
            }

        }
        return str;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}