案例(JQuery的ajax无刷新评论)

CommentsTest.html代码:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="jquery-1.8.3.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "post", url: "CommentsTest.ashx", data: { action: 'loadMsgs' },
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        var msg = data[i];
                        $("#ulMsgs").append($("<li>发表日期:" + msg.CreateDateTime + ";IP地址:" + msg.IP + ";消息:" + msg.Msg + "</li>"));
                    }
                },
                error: function () { alert("请求错误"); }
            });


            $("#btnPost").click(function () {
                var msg = $("#txtMsg").val();
                $.ajax({
                    type: "post", url: "CommentsTest.ashx", data: { msg: msg, action: 'post' },
                    success: function (data) {
                        if (data.Status == "ok") {
                            //alert("发表成功");
                            $("#ulMsgs").append($("<li>发表日期:刚刚;IP地址:本机;消息:" + msg + "</li>"));
                            $("#txtMsg").val("");
                        }
                        else if (data.Status == "error") {
                            alert(data.Msg);
                        }
                    },
                    error: function () { alert("请求错误"); }
                });
            });
        });
    </script>
</head>
<body>
    <ul id="ulMsgs">

    </ul>

    <br />
    <textarea id="txtMsg" cols="50" rows="5"></textarea><br />
    <input type="button" id="btnPost" value="发表" />
</body>

CommentsTest.ashx代码:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "application/json";
    string action = context.Request["action"];
    if (action == "loadMsgs")
    {
        DataTable dt =  SQLHelper.ExecuteReader("select * from T_Comments");
        List<Object> list = new List<object>();
        foreach (DataRow row in dt.Rows)
        {
            string msg = (string)row["Msg"];
            DateTime createDT = (DateTime)row["CreateDateTime"];
            string ip = (string)row["IP"];
            //JavaScriptSerializer在序列化DateTime的时候序列化出的东西不好看,可以在服务器端ToString()转换为字符串
            //也可以在浏览器端,使用JS把/DATE\(203377733)/转换为字符串格式
            list.Add(new { Msg = msg, CreateDateTime = createDT.ToString(), IP = ip });
        }
        context.Response.Write(new JavaScriptSerializer().Serialize(list));
    }
    else if (action == "post")
    {
        string msg = context.Request["msg"];
        string ip = context.Request.UserHostAddress;
        SQLHelper.ExecuteNonQuery("insert into T_Comments(Msg,CreateDateTime,IP) values(@Msg,@CreateDateTime,@IP)",
                new SqlParameter("@Msg", msg), new SqlParameter("@CreateDateTime", DateTime.Now),
                new SqlParameter("@IP", ip));
        context.Response.Write(new JavaScriptSerializer().Serialize(new { Status = "ok", Msg = "发表成功" }));
    }
    else
    {
        throw new Exception("action错误");
    }    
}

 

posted @ 2015-07-31 15:47  黄者之风  阅读(332)  评论(0编辑  收藏  举报