最近JSP課程實訓,而後本身作了一個新聞後臺控制檯。新聞列表的展現若是不用頁面部分刷新(Ajax)來作的話,翻頁的時候會重刷新頁面(感受很難看··),因此決定根據書上的例子+搜索的代碼用Ajax來實現分頁功能,順便搞了個用PHP實現的 :)javascript
· 在JavaBean中實現數據庫鏈接和格式化(JSON)從數據庫查詢到的數據php
public UserDAO() { //鏈接數據庫鏈接 Connection conn; Statement state; ResultSet rs; if (conn == null) { try { Class.forName("com.mysql.jdbc.Driver"); //數據庫使用MySQL.加載驅動 conn = DriverManager.getConnection("jdbc:mysql://localhost/DBname", "userName", "pwd"); } catch (Exception e) { e.printStackTrace(); } } } public String getUsers() { //格式化數據 StringBuffer sb = new StringBuffer(); sb.append("{newsList:["); try { if (conn == null) System.out.println("can not connection Database!"); state = conn.createStatement(); rs = state.executeQuery("select * from news"); while (rs.next()) sb.append("{title:'" + rs.getString("title") + "',content:'" + rs.getInt("content") + "'},"); sb.delete(sb.length() - 1, sb.length()); sb.append("]}"); } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); state.close(); } catch (SQLException e) { e.printStackTrace(); } } return sb.toString(); }
· 聲明XMLHttpRequest對象html
// JavaScript Document function createXMLHttpRequest() { var xmlHttp=false; if (window.ActiveXObject) { //在IE瀏覽器中建立XMLHttpRequest對象 try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(ee) { xmlHttp=false; } } } else if (window.XMLHttpRequest) { //在非IE瀏覽器中建立XMLHttpRequest對象 try { xmlHttp = new XMLHttpRequest(); } catch(e) { xmlHttp=false; } } return xmlHttp; }
· index.htmljava
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script language="javascript" src="xmlhttp.js"></script><!-- 引入建立了XMLHttpRequest對象的JS文件 --> <script language="javascript"> var xmlhttp; var pageSize=5; //每頁顯示5條記錄 var totalPage; //總頁數 var totalRs; //總記錄數 var jsonObj=new Object(); function go() { xmlhttp=createXMLHttpRequest(); //調用建立XMLHttpRequest對象的方法 xmlhttp.onreadystatechange=callback; //設置回調函數 xmlhttp.open("post","index.jsp"); //向服務器端發送請求 xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send(null); //設置發送參數 } function callback() //對服務器端傳回的JSON數據進行解析 { if(xmlhttp.readyState==4) { if(xmlhttp.status==200) { jsonObj=eval("("+xmlhttp.responseText+")"); //得到從服務器端返回的數據 totalRs=jsonObj.userList.length; totalPage=Math.ceil(totalRs/pageSize); splitPage(1); } } } function splitPage(currPage) //調用addRow方法輸出表格格式的數據到頁面 { while(document.getElementById("newsList").rows.length>1) document.getElementById("newsList").deleteRow(); var end; if(currPage<1) currPage=1; end=currPage*pageSize; if(currPage>=totalPage) { currPage=totalPage; end=totalRs; } var begin=currPage*pageSize-pageSize; for(var j=begin;j<end;j++) addRow("center",jsonObj.newsList[j].title,jsonObj.newsList[j].content); document.getElementById("dh").innerHTML="<a href='#' onclick='splitPage(1)'>首頁</a> <a href='#' onclick='splitPage("+eval(currPage-1)+")'>上一頁</a> <a href='#' onclick='splitPage("+eval(currPage+1)+")'>下一頁</a> <a href='#' onclick='splitPage("+totalPage+")'>尾頁</a>"; } function addRow(align,n1,n2) { var tt=document.getElementById("newsList"); var newRow=tt.insertRow(); for(var c=1;c<3;c++) { var newCell=newRow.insertCell(); newCell.align=align; newCell.innerHTML=eval("n"+c); } } </script> </head> <body background="" onload="go()"> <center><h2>數據分頁顯示</h2></center> <table width="250" border="1" id="newsList" align="center"> <tr><td align="center">標題</td><td align="center">內容</td></tr> </table> <table width="250" border="0" align="center"> <tr><td colspan="2" align="center" id="dh"></td></tr> </table> </body> </html>
· index.jsp
mysql
<%@ page language="java" import="java.util.*,com.*" pageEncoding="UTF-8"%> <% UserDAO ud=new UserDAO(); //實例化JavaBean out.print(ud.getUsers()); %>
p.s: 效果圖就是常常看到的在網頁下面的那種分頁欄··c++
· index.phpsql
<html> <head> <script> function viewpage(p){ if(window.XMLHttpRequest){ var xmlReq = new XMLHttpRequest(); } else if(window.ActiveXObject) { var xmlReq = new ActiveXObject('Microsoft.XMLHTTP'); } var formData = "page="+p; xmlReq.onreadystatechange = function(){ if(xmlReq.readyState == 4){ document.getElementById('content2').innerHTML = xmlReq.responseText; } } xmlReq.open("post", "resultPage.php", true); xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlReq.send(formData); return false; } </script> <head> <body onload="viewpage(1)"> <img src="" width="100%"> <h3 align="center">數據分頁顯示</h3> <div id="content2"></div> </body> </html>
· resultPage.php數據庫
<?php header("Content-Type:text/html;charset=GB2312"); $pagesize=3; $db=mysql_connect("localhost", "userName", "pwd") or die("數據庫連接錯誤");//建立數據庫鏈接 mysql_query("set character set gbk"); mysql_select_db("newsList"); $result = mysql_query("Select count(DISTINCT id) FROM ".news_list); $myrow = mysql_fetch_array($result); $numrows=$myrow[0]; $pages=intval($numrows/$pagesize); if ($numrows%$pagesize) $pages++; if (isset($_POST['page'])) { $page=intval($_POST['page']); } else { //設置爲第一頁 $page=1; } $first=1; $prev=$page-1; $next=$page+1; $last=$pages; //計算記錄偏移量 $offset=$pagesize*($page - 1); //讀取指定記錄數 $result=mysql_query("select * from ".news_list." GROUP BY `id` order by id desc limit $offset,$pagesize"); $num = mysql_num_rows($result); while ($row = mysql_fetch_array($result,MYSQL_NUM)) { $title[] = $row[0]; $content[]=$row[1]; } echo "<TABLE style=\"MARGIN-BOTTOM: 20px\" cellSpacing=0 cellPadding=0 width=90% border=1 align=center>\n"; echo "<TBODY>\n"; echo "<th>標題</th><th>內容</th>"; for($a=0;$a<$num;$a++) { echo "<TR>\n"; echo "<TD style=\"PADDING-TOP: 5px\" align=left>".$title[$a]."</TD>"; echo "<TD style=\"PADDING-TOP: 5px\" align=left>".$content[$a]."</TD>"; echo "</TR>"; } echo "</TR></TBODY></TABLE>\n"; echo "<TABLE style=\"MARGIN-TOP: 30px\" cellSpacing=0 cellPadding=0 width=\"100%\""; echo "border=0>"; echo "<TBODY><TR><TD colSpan=3 height=20>"; echo "<DIV align=center>"; echo "<P align=left><FONT color=red>第".$page."頁/總".$pages."頁 | 總".$numrows."條</FONT> | "; if ($page>1) echo "<a onclick=\"viewpage(".$first.")\" href='#'>首頁</a> | "; if ($page>1) echo "<a onclick=\"viewpage(".$prev.")\" href='#'>上頁</a> | "; if ($page<$pages) echo "<a onclick=\"viewpage(".$next.")\" href='#'>下頁</a> | "; if ($page<$pages) echo "<a onclick=\"viewpage(".$last.")\" href='#'>尾頁</a>"; echo " 轉到第 <INPUT maxLength=3 size=3 value=1 name=goto_page> 頁 <INPUT hideFocus onclick=\"viewpage(document.all.goto_page.value)\" type=button value=Go name=cmd_goto>"; echo "</P></DIV></TD></TR></TBODY></TABLE>"; ?>
以上。json