无刷新分页实现

1,前台页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="homepage.aspx.cs" Inherits="homepage" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>压铸微博</title>
<link href="css/public.css" rel="stylesheet" type="text/css"/>
<link href="css/muban1.css" rel="stylesheet" type="text/css"/>
<script language="JavaScript" type="text/javascript" src="js/public.js" charset="gb2312"></script>
<script language="JavaScript" type="text/javascript" src="js/weibo.js" charset="gb2312"></script>
</head>
<body>
    <form id="form1" runat="server">
   
   <div class="container">

 <div class="up"></div>
 
 <div class="center">
      <div class="head">
       <div class="logo"></div>
   
    <div class="search">
         <input type="text" name="textfield" value="搜名字/账号/标签/广播/话题" size="30" class="search1"  /> 
      &nbsp;
         <input type="image" name="Submit" value="" src="images/muban1/search.gif" />             
    </div>
   
    <div class="menu"><span class="red">首  页</span> | 微博广场 | 我的信箱 | 我的粉丝 | 关注朋友 | 我的微博</div>
    <div class="ad"></div>
   </div>
  
   <div class="left">
        <div class="about">
         <p class="renwu"><img src="images/muban1/ad.jpg" /></p>
      <p class="font_14b">华厦</p><p><img src="images/muban1/icon11.gif" /></p>
         <ul>
         <li>关注<span class="font_r14">122</span></li>
      <li>粉丝<span class="font_r14">122</span></li>
      <li>微博<span class="font_r14">122</span></li>
      </ul>
     </div>
     <div class="tuijian">
         <div class="title font_14b"><span>更多</span>推荐用户</div>
      <div class="content">
          <ul>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      <li><img src="images/ad1.jpg" />何炅</li>
      </ul>
      </div>
     </div>
   </div>
  
   <div class="right">
       <div class="fabu">
        <p class="font_18">来,说说你在做什么,想什么</p>

        <p><asp:TextBox ID="publisharea" runat="server" style="width:590px;height:86px;"></asp:TextBox></p>

     <p style="margin:10px 0px 0px 0px;"><div style="float:left;">还能输入140字</div><div style="float:right;"><asp:ImageButton ID="publishbutton" runat="server" ImageUrl="images/muban1/button.gif" OnClick="publish_Microblog" /></div><div style="clear:both;"></div></p>
    </div>
    <div class="news">
        <div class="title font_w14"><span class="botton"> 全部广播</span> 我的广播</div>
     <div class="content" id="weibo_list">
       
     </div>
     <div class="pages" id="weibo_list_b_page"></div>
    </div>
   </div>
 </div>
<script language="javascript" type="text/javascript">
    show_WeiBo(0,5,1,'weibo_list');
</script>
 <div class="bottom">版权所有:中国压铸网</div>

</div>

    </form>
</body>
</html>

2,分页JS页面

/*显示微博*/
function show_WeiBo(user_id, num, page, divid) {
    var xmlResult;
    $ID(divid).style.visibility = "hidden";
    var regxml = AjaxObject();
    if (regxml) {
        regxml.onreadystatechange = function() {
            if (regxml.readyState == 4) {
                if (regxml.status == 200) {
                    xmlResult = regxml.responseXML;
                    var results, i, strTemp = "", strPage = "", W_id, UserId, ParentId, Content, Created, PageUrl, FlashUrl, PicUrl, Pic, Type, allrec, totalpage, pages;
                    results = xmlResult.getElementsByTagName("result");
                    if (results[0].getElementsByTagName("Id")[0].firstChild.data == "#") {
                        strTemp = "<font class=\"gray\"><br />&nbsp;&nbsp;---暂无相关信息!---</font>";
                    }
     else {
                        allrec = xmlResult.getElementsByTagName("allrec")[0].firstChild.data;
                        totalpage = xmlResult.getElementsByTagName("totalpage")[0].firstChild.data;
                        pages = xmlResult.getElementsByTagName("page")[0].firstChild.data;
                        var currentpage = parseInt(pages);
                        /*分页-start-*/
                        if (totalpage > 1) {
                            strPage += "<div class=\"page_list\">";
                            var n = currentpage + 1;
                            var p = currentpage - 1;
                            if (p <= 0) {
                                p = 1;
                            }
                            if (n >= totalpage) {
                                n = totalpage;
                            }
                            var minpage = currentpage - 3;
                            var maxpage = currentpage + 3;
                            if (minpage <= 0) {
                                minpage = 1;
                                maxpage = 7;
                            }
                            if (maxpage > totalpage) {
                                maxpage = totalpage;
                                minpage = maxpage - 6;
                                if (minpage <= 0) {
                                    minpage = 1;
                                }
                            }
                            /*第一页和上一页*/
                            if (currentpage != 1) {
                                strPage += "<a href=\"javascript:\" onclick=\"javascript:show_WeiBo(" + user_id + "," + num + "," + p + ",'" + divid + "');\">上一页</a>";
                            } else {
                                strPage += "<span class=\"page1\">上一页</span>";
                            }
                            if (currentpage - 1 > 3 && totalpage > 7) {
                                if (currentpage - 1 == 4 || totalpage == 8) {
                                    strPage += "<a href=\"javascript:\" onclick=\"javascript:show_WeiBo(" + user_id + "," + num + ",1,'" + divid + "');\">1</a>";
                                } else {
                                    strPage += "<a href=\"javascript:\" onclick=\"javascript:show_WeiBo(" + user_id + "," + num + ",1,'" + divid + "');\">1</a><span>.</span>";
                                }
                            }
                            /*第一页和上一页*/
                            for (var i = minpage; i <= maxpage; i++) {
                                if (currentpage == i) {
                                    strPage += "<a class=\"page1\">" + i + "</a>";
                                } else {
                                    strPage += "<a href=\"javascript:\" onclick=\"javascript:show_WeiBo(" + user_id + "," + num + "," + i + ",'" + divid + "');\">" + i + "</a>";
                                }
                            }
                            /*最后一页和下一页*/
                            if (totalpage - currentpage > 3 && totalpage > 7) {
                                if (totalpage - currentpage == 4 || totalpage == 8) {
                                    strPage += "<a href=\"javascript:\" onclick=\"javascript:show_WeiBo(" + user_id + "," + num + "," + totalpage + ",'" + divid + "');\">" + totalpage + "</a>";
                                } else {
                                    strPage += "<span>.</span><a href=\"javascript:\" onclick=\"javascript:show_WeiBo(" + user_id + "," + num + "," + totalpage + ",'" + divid + "');\">" + totalpage + "</a>";
                                }
                            }
                            if (currentpage < totalpage) {
                                strPage += "<a href=\"javascript:\" onclick=\"javascript:show_WeiBo(" + user_id + "," + num + "," + n + ",'" + divid + "');\" >下一页</a>";
                            } else {
                                strPage += "<span class=\"page1\">下一页</span>";
                            }
                            /*最后一页和下一页*/
                            strPage = strPage + "</div>";
                            $ID(divid + "_b_page").innerHTML = strPage;
       /*分页-end-*/
                        }
                        for (i = 0; i < results.length; i++) {
                            strTemp += "<ul class=\"weibo_list\" onmouseover=\"\" onmouseout=\"\">";
                            W_id = results[i].getElementsByTagName("Id")[0].firstChild.data;
                            UserId = results[i].getElementsByTagName("UserId")[0].firstChild.data;
                            ParentId = results[i].getElementsByTagName("ParentId")[0].firstChild.data;
                            Content = unescape(results[i].getElementsByTagName("Content")[0].firstChild.data);
                            Created = unescape(results[i].getElementsByTagName("Created")[0].firstChild.data);
                            PageUrl = unescape(results[i].getElementsByTagName("PageUrl")[0].firstChild.data);
                            FlashUrl = unescape(results[i].getElementsByTagName("FlashUrl")[0].firstChild.data);
       PicUrl = unescape(results[i].getElementsByTagName("PicUrl")[0].firstChild.data);
       Pic = unescape(results[i].getElementsByTagName("Pic")[0].firstChild.data);
       Type = results[i].getElementsByTagName("Type")[0].firstChild.data;
                            strTemp += "<li>"+Content+" "+Created+"</li>";
                            strTemp += "</ul>";
                        }
                    }
                    $ID(divid).innerHTML = strTemp;
                    $ID(divid).style.visibility = "";
                }
            }
        }
        regxml.open("GET", "Ajax/Handler.ashx?user_id=" + user_id + "&pageSize=" + num + "&page=" + page, true);
        regxml.send(null);
    }
}

3,生成Ajax对象页面:

function $ID(id){return document.getElementById(id);}
var i=9;
var close_str,close_str1;
function check_len(value,num)
{
 var str=value;
 var str1=value+"_p";
 var num1=num-$ID(str).value.length;
 if($ID(str).value.length <= num && $ID(str).value.length >= 1)
 {
  $ID(str1).innerHTML="【您还可以输入"+num1+"个字。】";
 }
 else if($ID(str).value.length == 0)
 {
  $ID(str1).innerHTML="【您至少需要输入1个字。不然提交时将出现错误。】";
 }
 else
 {
  $ID(str1).innerHTML="【您的输入已经超过"+num+"个字。提交时将出现错误。】";
 }
}
function check_len_n(value,num)
{
 var str=value;
 var str1=value+"_p";
 var num1=num-$ID(str).value.length;
 if($ID(str).value.length <= num )
 {
  $ID(str1).innerHTML="【您还可以输入"+num1+"个字。】";
 }
 else
 {
  $ID(str1).innerHTML="【您的输入已经超过"+num+"个字。提交时将出现错误。】";
 }
}
//操作提示
function popup_I(type,content,stime)
{
 if(!$ID("cnzz_win")){
  var newNode=document.createElement("div");
  newNode.id="cnzz_win";
  newNode.className="cnzz_win";
  document.body.appendChild(newNode);
  //document.body.insertBefore(newNode,document.body.getElementsByTagName("div").item(0));
 }
 clearTimeout(close_str);
 clearTimeout(close_str1);
 var win=$ID("cnzz_win");
 win.style.display="block";
 i=9;
 win.className="display10";
 var strs="";
 if(type=="ok")
 {
  strs+="<dl class=\"ok\">";
  strs+="<dt><span>操作成功</span><a href=\"javascript:\" onclick=\"close_I('cnzz_win');\">×</a></dt>";
  strs+="<dd>"+content+"</dd>";
  strs+="</dl>";
 }
 else if(type=="error")
 {
  strs+="<dl class=\"error\">";
  strs+="<dt><span>操作失败</span><a href=\"javascript:\" onclick=\"close_I('cnzz_win');\">×</a></dt>";
  strs+="<dd>"+content+"</dd>";
  strs+="</dl>";
 }
 else if(type=="loading")
 {
  strs+="<dl class=\"ok\">";
  strs+="<dt><span>数据处理中</span><a href=\"javascript:\" onclick=\"close_I('cnzz_win');\">×</a></dt>";
  strs+="<dd>"+content+"</dd>";
  strs+="</dl>";
 }
 win.innerHTML=strs;
 close_str=setTimeout("close_I('cnzz_win')",stime);
 win.onmouseover=function(){clearTimeout(close_str);}
 win.onmouseout=function(){close_str=setTimeout("close_I('cnzz_win')",stime);}
 
}
function close_I(divid)
{
 if(i>0){
  $ID(divid).className="display"+i;
  close_str1=setTimeout("close_I('"+divid+"')",50);
  i--;
 }
 else{
  $ID(divid).style.display="none";
  i=9;
 }
}
//
function open_div(divId)
{
 var div=$ID(divId);
 if(div.style.display=="none")
 {
  div.style.display="block";
 }
 else
 {
  div.style.display="none";
 }
}
//textarea换行转换
function textarea()
{
 var alltext=document.getElementsByTagName("textarea");
 for(var i=0;i<alltext.length;i++){
  alltext[i].value=alltext[i].value.replace(/<[bB][rR]\s*(\/)*>/g, "\n");
 }
}
//倒计时
function Seconds(Snum,Sid,url)
{
 if(Snum>0){
  $ID(Sid).innerHTML=Snum;
  Snum--;
  setTimeout("Seconds("+Snum+",'"+Sid+"','"+url+"')",1000);
 }
 else{
  if(url=="back")
  {
   history.back();
  }
  else{
   top.location.href=url;
  }
 }
}
//
function del_Text(str,value) {
    value = value.replace(/^,/, '').replace(/,$/, '');
    str = str.replace(/^,/, '').replace(/,$/, '');          
    if (value == str)
    {
        return '';
    }           
    var sArray = str.split(',');
    for (var i = sArray.length - 1; i >= 0; --i)
    {
        if (sArray[i] == value)
            sArray[i] = undefined;
    }         
    var result = sArray.join(',');//重新连接字符串数组
    //因为undefined会连接成,,所以要将,,换成,           
    result = result.replace(/,,/,',');
    result = result.replace(/^,/, '').replace(/,$/, '');
 return result;
}
/*截取字符串长度*/
function Substr(str,c)
{
 str = str.replace(/(\<\/*[^<>]*\>)/g, '');
 var t1 = str.replace(/([^\x00-\xff])/ig, '$1@');
 var t2 = t1.substring(0, c);
 var t3 = t2.replace(/([^\x00-\xff])@/ig, '$1');
 if(t1.length>c)
  return t3+"...";
 else
  return t3;
}
/*格式化HTML代码*/
function NotHtml(str)
{
 str = str.replace(/(\<\/*[^<>]*\>)/g, '');
 return str;
}
/*Cookie操作*/
function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
function getCookie(c_name)
{
 var c_value="";
 if(document.cookie!="")
 { 
  var thiscookie=document.cookie.split("; ");
  for(var i=0;i<thiscookie.length;i++){
   if(thiscookie[i].split("=")[0]==c_name){
    c_value=unescape(thiscookie[i].split("=")[1]);
   }
  } 
 }
 return c_value
}
function delCookie(name){
var date = new Date();
date.setDate(date.getDate()-10);
document.cookie = name + "=a; expires=" + date.toGMTString();
}
/*Cookie操作*/
/*AjaxObject*/
function AjaxObject(){
 var AjaxHttp=false;
   try{
     AjaxHttp=new XMLHttpRequest();
    }
   catch (e){
     try{
        AjaxHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
     catch (e){
        AjaxHttp=new ActiveXObject("Microsoft.XMLHTTP");
       }
   }
 return AjaxHttp; 
}
/*无缝向上滚动*/
function Move_Up(Wrap,field){
 var _wrap=false,_interval=false,_moving=false;
 _wrap=$(''+Wrap+'');//定义滚动区域
 _interval=2000;//定义滚动间隙时间
 _moving;//需要清除的动画
 _wrap.hover(function(){
  clearInterval(_moving);//当鼠标在滚动区域中时,停止滚动
 },function(){
  _moving=setInterval(function(){
   var _field=_wrap.find(''+field+':first');//此变量不可放置于函数起始处,li:first取值是变化的
   var _h=_field.height();//取得每次滚动高度
   _field.animate({marginTop:-_h+'px'},600,function(){//通过取负margin值,隐藏第一行
    _field.css('marginTop',0).appendTo(_wrap);//隐藏后,将该行的margin值置零,并插入到最后,实现无缝滚动
   })
  },_interval)//滚动间隔时间取决于_interval
 }).trigger('mouseleave');//函数载入时,模拟执行mouseleave,即自动滚动
}
/*验证单、多选按钮选中数*/
function checkRadio(formID,name){
 var number = 0,Radio;
 formID==""?Radio=$("input[name='"+name+"']"):Radio=$("#"+formID+" input[name='"+name+"']");
 if(Radio.length>0){
  for(var i=0;i<Radio.length;i++){
   if(Radio.eq(i).attr("checked")==true){
    number+=1;
   }
  }
 }
 return number;
}
/*公用检验*/
String.prototype.isUrl = function(){
 return (/^http[s]?:\/\/([\w-]+\.)+[\w-]+([\w-./?%&=]*)?$/i).test(this);
}
String.prototype.isEmail = function(){
 return (/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i).test(this);
}
String.prototype.trim=function() {
 return this.replace(/(^\s*)|(\s*$)/g, '');
}
/*提示确认框*/
function return_ok(Content){
 var i=confirm(Content);
 if(i){
  return true;
 }
 else{
  return false;
 }
}
/*图片尺寸格式化*/
function DrawImage(ImgD,iwidth,iheight){
 var image=new Image();
 image.src=ImgD.src;
 if(image.width>0 && image.height>0){
  if(image.width/image.height>= iwidth/iheight){
   if(image.width>iwidth){ 
    ImgD.width=iwidth;
    ImgD.height=(image.height*iwidth)/image.width;
   }
   else{
    ImgD.width=image.width; 
    ImgD.height=image.height;
   }
  }
  else{
   if(image.height>iheight){ 
    ImgD.height=iheight;
    ImgD.width=(image.width*iheight)/image.height; 
   }
   else{
    ImgD.width=image.width; 
    ImgD.height=image.height;
   }
  }
 }
}

 4,动态文件

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

using System;
using System.Web;
using System.Text;
using System.Data;
using Maticsoft.DBUtility;

public class Handler : IHttpHandler {
    private int ps;
    private int cp;
    private int allrec;
    private int totalpage;
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/xml";
       
        if (context.Request.QueryString["pageSize"]!=null)
        {
            ps = Convert.ToInt32(context.Request.QueryString["pageSize"]);
        }
        else
        {
            ps = 20;
        }

        if (context.Request.QueryString["Page"]!=null)
        {
            cp = Convert.ToInt32(context.Request.QueryString["Page"]);
        }
        else
        {
            cp = 1;
        }
        allrec = Convert.ToInt32(DbHelperSQL.GetSingle("select count(1) from individual_microblog "));
        totalpage = Convert.ToInt32((allrec + ps - 1) / ps);
        context.Response.Write(server_Side_Processing(ps,cp));
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    /// <summary>
    ///服务器端处理程序到数据库查询数据并生成xml档返回
    /// </summary>
    public string server_Side_Processing(int pageSize, int currentPage)
    {
        StringBuilder resultXML = new StringBuilder();
        string str_xml;
        DataSet ds;
        int i;


        resultXML.Append("<?xml version=\"1.0\" encoding=\"gb2312\" ?>");
        resultXML.Append("<weibo>\n");
        resultXML.Append("<allrec>" + allrec + "</allrec>\n");
        resultXML.Append("<totalpage>" + totalpage + "</totalpage>\n");
        resultXML.Append("<page>" + cp + "</page>\n");
        resultXML.Append("<num>" + ps + "</num>\n"); 
        try
        {
            if (currentPage == 1)
            {
                str_xml = "select top " + pageSize + " * from individual_microblog order by Id desc";
            }
            else
            {
                str_xml = "select top " + pageSize + " * from individual_microblog where Id not in (select top " + pageSize * (currentPage - 1) + " Id from individual_microblog order by Id desc) order by Id desc";
            }
           
            ds = DbHelperSQL.Query(str_xml);

            if (ds != null)
            {

                for (i = 0; i < pageSize; i++)
                {
                    if (ds.Tables[0].Rows[i] == null)
                    {
                        break;
                    }

                    resultXML.Append("<result>\n");
                    resultXML.Append("\t<Id>" + ds.Tables[0].Rows[i]["Id"].ToString() + "</Id>\n");
                    resultXML.Append("\t<UserId>" + ds.Tables[0].Rows[i]["UserId"].ToString() + "</UserId>\n");
                    resultXML.Append("\t<ParentId>" + ds.Tables[0].Rows[i]["ParentId"].ToString() + "</ParentId>\n");

                    if (ds.Tables[0].Rows[i]["Content"].ToString().Trim() != "")
                    {
                        resultXML.Append("\t<Content>" + HttpUtility.UrlEncodeUnicode(ds.Tables[0].Rows[i]["Content"].ToString().Trim()) + "</Content>\n");
                    }
                    else
                    {
                        resultXML.Append("\t<Content>#</Content>\n");
                    }

                    resultXML.Append("\t<Created>" + ds.Tables[0].Rows[i]["Created"].ToString() + "</Created>\n");

                    if (ds.Tables[0].Rows[i]["PageUrl"].ToString().Trim() != "")
                    {
                        resultXML.Append("\t<PageUrl>" + HttpUtility.UrlEncodeUnicode(ds.Tables[0].Rows[i]["PageUrl"].ToString().Trim()) + "</PageUrl>\n");
                    }
                    else
                    {
                        resultXML.Append("\t<PageUrl>#</PageUrl>\n");
                    }

                    if (ds.Tables[0].Rows[i]["FlashUrl"].ToString().Trim() != "")
                    {
                        resultXML.Append("\t<FlashUrl>" + HttpUtility.UrlEncodeUnicode(ds.Tables[0].Rows[i]["FlashUrl"].ToString().Trim()) + "</FlashUrl>\n");
                    }
                    else
                    {
                        resultXML.Append("\t<FlashUrl>#</FlashUrl>\n");
                    }

                    if (ds.Tables[0].Rows[i]["PicUrl"].ToString().Trim() != "")
                    {
                        resultXML.Append("\t<PicUrl>" + HttpUtility.UrlEncodeUnicode(ds.Tables[0].Rows[i]["PicUrl"].ToString().Trim()) + "</PicUrl>\n");
                    }
                    else
                    {
                        resultXML.Append("\t<PicUrl>#</PicUrl>\n");
                    }

                    if (ds.Tables[0].Rows[i]["Pic"].ToString().Trim() != "")
                    {
                        resultXML.Append("\t<Pic>" + HttpUtility.UrlEncodeUnicode(ds.Tables[0].Rows[i]["Pic"].ToString().Trim()) + "</Pic>\n");
                    }
                    else
                    {
                        resultXML.Append("\t<Pic>#</Pic>\n");
                    }

                    resultXML.Append("\t<Type>" + ds.Tables[0].Rows[i]["Type"].ToString() + "</Type>\n");

                    resultXML.Append("</result>\n");
                }
            }
            else
            {
                resultXML.Append("<result>\n");
                resultXML.Append("\t<Id>#</Id>\n");
                resultXML.Append("</result>\n");
            }

        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
        }

        resultXML.Append("</weibo>");

        return resultXML.ToString();
    }

}

posted @ 2011-09-06 12:22  xgcdd  阅读(405)  评论(0编辑  收藏  举报