AJAX提交到Handler.ashx一般处理程序返回json数据-转

直接贴代码!我也测试通过! 一切看注释! 谢谢!

<%@ WebHandler Language="C#" class="Handler" %>

using System;
using System.Web;
using System.Text;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string id = "0";
        //判断提交方式
        if (context.Request.RequestType.ToLower() == "get")
        {
            id = context.Request.QueryString["id"];
        }
        else
        {
            id = context.Request.Form["id"];
        }
        
        string name = @"jinho's good "" you";
        /**
         * 今天暂时用手动创建个json字符串类型,其实.net中有
         * System.Runtime.Serialization.Json.DataContractJsonSerializer这个类来把
         * 实体对象转换为json字符串! 改天再用那种方式写个吧!
         * 自己也学习学习[更多关于json介绍!google一下多了是]
         * */
        StringBuilder sb = new StringBuilder("{");
        sb.Append("id:"+id);
        /*
         * 注意但属性值为字符串的时候需要有'号或者"号['字符串']
         * 当 参数 name 又含 有单引号或者双引号 就会出错了![截断了字符串]
         * 在这里sb.Append(",name:'escape(" + name + ")'"); 用js的escape也不行
         * context.Server.HtmlEncode();,context.Server.UrlEncode();也不行
         * 可以看看这里
         * escape("'") = %27 可以在js用 unescape("'") 就还原了
         * escape(""") = %22 嘿嘿,用这个方法也是我的无奈之举!
         * 谁有好的方法记得告诉我哦! 先谢谢了!
         * 问题已解决:http://www.cnblogs.com/jinho/archive/2010/05/07/1729586.html
         * */
        sb.Append(",name:'" + name.Replace("'", "%27").Replace(""", "%22") + "'"); 
        sb.Append(",age:22");
        sb.Append("}");
        //输出 json 字符串
        context.Response.Write(sb.ToString());
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>前台</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:scriptmanager runat="server" ID="sm" />
    <script type="text/javascript">
        function ajaxFunction() {
            var xmlHttp;
            try {
                // Firefox, Opera 8.0+, Safari
                xmlHttp = new XMLHttpRequest();
            }
            catch (e) {

                // Internet Explorer
                try {
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {

                    try {
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) {
                        alert("您的浏览器不支持AJAX!");
                        return false;
                    }
                }
            }
            return xmlHttp;
        }
</script>
    <script type="text/javascript">
        var xmlhttp = null;
        function loadJsonData() {
            xmlhttp = ajaxFunction();
            if (xmlhttp != null) {
                xmlhttp.onreadystatechange = state_Change;
                var data = "id=231";
                //把这两句注释,看看下面的POST提交方式
                xmlhttp.open("GET", "Handler.ashx?" + data, true);
                xmlhttp.send(null);
                /*
                xmlhttp.open("POST", "Handler.ashx", true);
                //如果使用POST提交 不设置这条语句,url页面 Request.Form["key"] 是取不到值的!
                //这句我也不知道为什么要设置,网上找到的![GET提交可以不设置,但需要把参数拼接到URL]
                xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xmlhttp.send(data); //如果是post提交,需要把数据发送过去
                */
            }
            else {
                alert("Your browser does not support XMLHTTP.");
            }
        }
        function state_Change() {
            if (xmlhttp.readyState == 4) {// 4 = "loaded"
                if (xmlhttp.status == 200) {// 200 = "OK"
                    eval("var s = " + xmlhttp.responseText);
                    $get("divDisplay").innerHTML = "ID" + s.id + "Name:" + unescape(s.name) + "Age:" + s.age;
                }
                else {
                    alert("Error:" + xmlhttp.statusText);
                }
            }
        }
</script>

    <div>
    <input type="button" value="GetJson" onclick="loadJsonData();" />
    <div id="divDisplay"></div>
    </div>
    </form>
</body>
</html>
原文地址:https://www.cnblogs.com/asdyzh/p/9785376.html