分页技术原理与实现之无刷新的Ajax分页技术(三)

这篇文章主要介绍了分页技术原理与实现的第三篇:无刷新的Ajax分页技术,感兴趣的小伙伴们可以参考一下

紧接着上篇—分页技术原理与实现之Java+Oracle代码实现分页(二) ,本篇继续分析分页技术。上篇讲的是分页技术的代码实现,这篇继续分析一下分页技术的效果控制。
上篇已经用代码简单的实现了一个分页。但是我们都看到,代码中每次通过servlet请求取得结果集后,都会转向到一个jsp页面显示结果,这样每次查询页面都会刷新一下,比如查询出现结果集后要查看第三页,页面就会刷新一下。这样页面给人的效果感觉就会有点不舒服,所以我们希望能够在通过条件查询结果集后无论访问哪一页,页面都不会刷新,而只是结果集变化。要解决这个,我想大家很容易就会想到Ajax了。
是啊,这就要请Ajax出山了。当通过查询条件查询到结果集后,以后每次访问任何一页都通过Ajax来访问,使用异步Ajax与Servlet进行交互,将结果查询出来返回给Ajax,这样页面内容因为Ajax返回结果而改变,而页面却不会刷新,这就实现了无刷新的分页技术。
下面我们来看一个简单的无刷新分页实现,代码如下:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <link rel="stylesheet" href="../lib/jquery_pagination/pagination.css" mce_href="lib/jquery_pagination/pagination.css" />
 <mce:script type="text/<a href="http://lib.csdn.net/base/javascript" class='replace_word' title="JavaScript知识库" target='_blank' style='color:#df3434; font-weight:bold;'>JavaScript</a>" src="../lib/<a href="http://lib.csdn.net/base/jquery" class='replace_word' title="jQuery知识库" target='_blank' style='color:#df3434; font-weight:bold;'>jQuery</a>/jquery.min.js" mce_src="lib/jquery/jquery.min.js"></mce:script>
 <mce:script type="text/javascript"
  src="../lib/jquery_pagination/jquery.pagination.js"></mce:script>
 <mce:script type="text/javascript"><!--
 /**
 * Callback function that displays the content.
 *
 * Gets called every time the user clicks on a pagination link.
 *
 * @param {int}page_index New Page index
 * @param {jQuery} jq the <a href="http://lib.csdn.net/base/docker" class='replace_word' title="Docker知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Container</a> with the pagination links as a jQuery object
 */
 function pageselectCallback(page_index, jq) {
 var new_content = $('#hiddenresult div.result:eq(' + page_index + ')')
  .clone();
 $('#Searchresult').empty().append(new_content);
 return false;
 }

 function initPagination() {
 var num_entries = $('#hiddenresult div.result').length;
 // Create pagination element
 $("#Pagination").pagination(num_entries, {
  num_edge_entries : 2,
  num_display_entries : 8,
  callback : pageselectCallback,
  items_per_page : 1
 });
 }

 // When the HTML has loaded, call initPagination to paginate the elements    
 $(document).ready(function() {
 initPagination();
 });
// --></mce:script>
 <mce:style type="text/css"><!--
* {
 padding: 0;
 margin: 0;
}

body {
 background-color: #fff;
 margin: 20px;
 padding: 0;
 height: 100%;
 font-family: Arial, Helvetica, sans-serif;
}

#Searchresult {
 margin-top: 15px;
 margin-bottom: 15px;
 border: solid 1px #eef;
 padding: 5px;
 background: #eef;
 width: 40%;
}

#Searchresult p {
 margin-bottom: 1.4em;
}
--></mce:style><style type="text/css" mce_bogus="1">* {
 padding: 0;
 margin: 0;
}

body {
 background-color: #fff;
 margin: 20px;
 padding: 0;
 height: 100%;
 font-family: Arial, Helvetica, sans-serif;
}

#Searchresult {
 margin-top: 15px;
 margin-bottom: 15px;
 border: solid 1px #eef;
 padding: 5px;
 background: #eef;
 width: 40%;
}

#Searchresult p {
 margin-bottom: 1.4em;
}</style>
 <title>Pagination</title>
 </head>
 <body>
 <h4>
  jQuery Pagination Plugin Demo
 </h4>

 <div id="Pagination" class="pagination">
 </div>
 <br style="clear: both;" mce_style="clear: both;" />
 <div id="Searchresult">
  This content will be replaced when pagination inits.
 </div>

 <div id="hiddenresult" style="display: none;" mce_style="display: none;">
  <div class="result">
  <p>
   Globally maximize granular "outside the box" thinking vis-a-vis
   quality niches. Proactively formulate 24/7 results whereas 2.0
   catalysts for change. Professionally implement 24/365 niches rather
   than client-focused users.
  </p>
  <p>
   Competently engineer high-payoff "outside the box" thinking through
   cross functional benefits. Proactively transition intermandated
   processes through open-source niches. Progressively engage
   maintainable innovation and extensible interfaces.
  </p>
  </div>
  <div class="result">
  <p>
   Credibly fabricate e-business models for end-to-end niches.
   Compellingly disseminate integrated e-markets without ubiquitous
   services. Credibly create equity invested channels with
   multidisciplinary human capital.
  </p>
  <p>
   Interactively integrate competitive users rather than fully tested
   infomediaries. Seamlessly initiate premium functionalities rather
   than impactful architectures. Rapidiously leverage existing
   resource-leveling processes via user-centric portals.
  </p>
  </div>
  <div class="result">
  <p>
   Monotonectally initiate unique e-services vis-a-vis client-centric
   deliverables. Quickly impact parallel opportunities with B2B
   bandwidth. Synergistically streamline client-focused
   infrastructures rather than B2C e-commerce.
  </p>
  <p>
   Phosfluorescently fabricate 24/365 e-business through 24/365 total
   linkage. Completely facilitate high-quality systems without
   stand-alone strategic theme areas.
  </p>
  </div>
 </div>
 </body>
</html>

这就是一个非常简单的无刷新分页实现,使用了JQuery+ jquery.pagination框架。现在随着框架的流行,尤其是Jquery的流行,使用框架来开发是非常有效的。上面代码原理在代码中已有注释,也可参考Jquery的官方网站:。
现在就可以来开发我们的Ajax无刷新分页实现。基于上面的原理,在响应页码被按下的代码中pageselectCallback(),我们使用一个Ajax异步访问数据库,通过点击的页号将结果集取出后再用异步设置到页面,这样就可以完成了无刷新实现。 

页码被按下的响应函数pageselectCallback()修改如下: 

这样就可以用异步方式获取结果,用showResponse函数来处理结果了,showResponse函数如下:


function showResponse(request){
   var content = request;
   var root = content.documentElement;
   var responseNodes = root.getElementsByTagName("root");
   var itemList = new Array();
   var pageList=new Array();
   alert(responseNodes.length);
   if (responseNodes.length > 0) {
    var responseNode = responseNodes[0];
    var itemNodes = responseNode.getElementsByTagName("data");
    for (var i=0; i<itemNodes.length; i++) {
     var idNodes = itemNodes[i].getElementsByTagName("id");
     var nameNodes = itemNodes[i].getElementsByTagName("name");
     var sexNodes=itemNodes[i].getElementsByTagName("sex");
     var ageNodes=itemNodes[i].getElementsByTagName("age");
     if (idNodes.length > 0 && nameNodes.length > 0&&sexNodes.length > 0&& ageNodes.length > 0) {
      var id=idNodes[0].firstChild.nodeValue;
      var name = nameNodes[0].firstChild.nodeValue;
      var sex = sexNodes[0].firstChild.nodeValue;
      var age=ageNodes[0].firstChild.nodeValue;
      itemList.push(new Array(id,name, sex,age));
     }
    }
    
    var pageNodes = responseNode.getElementsByTagName("pagination");
    if (pageNodes.length>0) {
     var totalNodes = pageNodes[0].getElementsByTagName("total");
     var startNodes = pageNodes[0].getElementsByTagName("start");
     var endNodes=pageNodes[0].getElementsByTagName("end");
     var currentNodes=pageNodes[0].getElementsByTagName("pageno");
     if (totalNodes.length > 0 && startNodes.length > 0&&endNodes.length > 0) {
      var total=totalNodes[0].firstChild.nodeValue;
      var start = startNodes[0].firstChild.nodeValue;
      var end = endNodes[0].firstChild.nodeValue;
      var current=currentNodes[0].firstChild.nodeValue;
      pageList.push(new Array(total,start,end,current));
     }
    }
   }
   showTable(itemList,pageList);
  }

如上代码就是用来处理通过Ajax异步请求Servlet后返回的XML格式的结果,其中Servlet代码在上篇中。其中itemList、pageList分别是解析返回后生成的用户List和分页导航,这样用户就可以以自己的展现方式展现数据了。


function pageselectCallback(page_index, jq){
  var pars="pageNo="+(page_index+1);
   $.ajax({
    type: "POST",
   url: " UserBasicSearchServlet",
   cache: false,
   data: pars,
   success: showResponse
  });
    return false;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。

本文标题为:分页技术原理与实现之无刷新的Ajax分页技术(三)

基础教程推荐