2009年4月14日星期二

一个使用JQuery来实现Ajax的例子

对JQuery的学习已经有一段时间了,最近做了一个Ajax的例子,因为环境原因,只能给出js部分,个人觉得这个Ajax的例子很有特点:包括了评论载入、添加评论、
//以动画形式展开/折叠评论内容
function zhankai(oDiv,othis)
{
//当前对象坐标
var offset=$(othis).offset();
var str=CreateTipDiv(offset.top,offset.left-200);
$("body").append(str);
//异步加载评论内容
$.ajax({
type: "POST",
url: "Services/CommentService.ashx",
dataType:"html",
data: "do=getlist&cAppContentId="+encodeURIComponent(oDiv),
success: function(commentInfo)
{
$("#ul_"+oDiv).html(commentInfo);
$("#loading").remove();
$("#"+oDiv).show("slow");

}
});

}
//折叠评论
function zhedie(id)
{
$("#" + id).hide("slow");
}
//创建加载评论提示层div
function CreateTipDiv(top,left)
{
return "
加载评论中,请稍等...
";
}
//提交评论
function SubmitComment(Id)
{
var commentInfo= $("#"+"ta_"+Id).html();
if(commentInfo.length==0)
{
alert("还没写东西哦!");
return false;
}
if(commentInfo.length>500)
{
alert("不好意思哦,我只能装500个字符!");
return false;
}
var userName=encodeURIComponent($("#hd_uname").val());
var uid=$("#hd_uid").val();
var newComment="
  • "+$("#hd_uname").val()+""+commentInfo+"
  • ";
    $.ajax({
    type: "POST",
    url: "Services/CommentService.ashx",
    //dataType:"json",
    data: "do=insert&uid="+uid+"&uname="+encodeURIComponent(userName)+"&cAppContentId="+encodeURIComponent(Id)+"&commentInfo="+encodeURIComponent(commentInfo),
    success: function(msg){
    var ulId="ul_"+Id;
    var whichStyle=$("#"+ulId+">li").length%2
    if(whichStyle==0)
    {
    $(newComment).appendTo("#"+ulId).effect("highlight", {color:"#ffff79"}, 2500) ;
    }
    else
    { //为偶数行,样式不同
    $(newComment).appendTo("#"+ulId).addClass("bg").effect("highlight", {color:"#ffff79"}, 2500) ;
    }
    var num =parseInt($("#pl_"+Id).text(),10)+1;
    $("#pl_"+Id).text(num);
    },
    error:function(ex)
    {
    alert(ex);
    }
    });
    }
    //根据新闻的ID获取评论数
    function GetCommentCountById(NewsId,oThis)
    {
    $.ajax({
    type: "POST",
    url: "Services/CommentService.ashx",
    data: "do=getcount&cAppContentId="+encodeURIComponent(NewsId),
    success: function(msg)
    {
    oThis.text(msg);
    }
    });
    }
    //页面加载完成后执行
    $(document).ready(
    function()
    {//循环,异步获取评论数
    $(".commentCount").each(
    function()
    {
    var NewsId=this.id.replace("pl_","");
    GetCommentCountById(NewsId,$(this));
    }

    );
    }
    );

    没有评论: