无刷新加载评论

服务器端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<%@ WebHandler Language="C#" Class= "PostComment" %>
using System;
using System.Web;
using System.Text;
public class PostComment : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context .Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        var comments = new DataSetPostTableAdapters. T_PostsTableAdapter().GetData ();//获得数据
        StringBuilder sb = new StringBuilder();//建立字符串builder
        foreach ( var comment in comments )
        {
            //将每个评论用‘&’字符分开,各个评论项目用‘|’分开
            sb.Append( comment.IPAddr ).Append( "|").Append (comment.PostDate).Append ("|").Append(comment .Msg). Append("&" );
        }
        context .Response.Write(sb .ToString().Trim('&' ));//将评论相应给客户端
    }
  
    public bool IsReusable {
        get {
            return false ;
        }
    }
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<head>
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript" ></script>
    <script type="text/javascript" >
        $ (function () {
            $ .post("PostComment.ashx" , function (data , status) {
                if (status != "success" ) {
                    $ ("#ulcomment" ).append ($("<li>加载失败!</li>" ));
                    return;
                }
                var lines = data.split ("&" );//按照‘&’将评论分成数组
                for (var i = 0; i < lines.length; i++) {
                    var line = lines [i];
                    var fields = line.split ('|' );//对每个数组内部再进行划分成不同的区域,有时间,ip,内容 三项
                    var comment = $( "<li>IP地址:" + fields[ 0] + "发帖日期:" + fields[ 1] + "内容:" + fields[ 2] + "</li>" );
                    $ ("#ulcomment" ).append (comment);//动态加载到网页中
                }
            });
        });
        
    </script>
</head>
<body>
<ul id ="ulcomment">
</ul>
</body>
</html>



posted @ 2016-03-16 21:48  copperface  阅读(225)  评论(0编辑  收藏  举报