(1)頁面代碼:
- 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" media="screen"
href="js/themes/basic/grid.css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.jqGrid.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#myTab").jqGrid({
datatype: "json", //將這裡改為使用JSON數據
url:'DataServlet', //這是Action的請求地址
mtype: 'POST',
height: 250,
width: 400,
colNames:['編號','姓名', '電話'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int"},
{name:'name',index:'name', width:90},
{name:'phone',index:'phone', width:100}
],
pager: 'pager', //分頁工具欄
imgpath: 'js/themes/basic/images', //圖片存放路徑
rowNum:10, //每頁顯示記錄數
viewrecords: true, //是否顯示行數
rowList:[10,20,30], //可調整每頁顯示的記錄數
multiselect: false, //是否支持多選
caption: "信息顯示"
});
});
</script>
</head>
<body>
<table id="myTab" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll"></div>
</body>
</html>
(2)後台的servlet,裡面的數據是模擬的
- 代碼如下:
/**
* Servlet implementation class DataServlet
*/
public class DataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String page = request.getParameter("page"); // 取得當前頁數,注意這是jqgrid自身的參數
String rows = request.getParameter("rows"); // 取得每頁顯示行數,,注意這是jqgrid自身的參數
int totalRecord = 80; // 總記錄數(應根據數據庫取得,在此只是模擬)
int totalPage = totalRecord % Integer.parseInt(rows) == 0 ? totalRecord
/ Integer.parseInt(rows) : totalRecord / Integer.parseInt(rows)
+ 1; // 計算總頁數
try {
int index = (Integer.parseInt(page) - 1) * Integer.parseInt(rows); // 開始記錄數
int pageSize = Integer.parseInt(rows);
// 以下模擬構造JSON數據對象
String json = "{total: " + totalPage + ", page: " + page
+ ", records: " + totalRecord + ", rows: [";
for (int i = index; i < pageSize + index && i < totalRecord; i++) {
json += "{cell:['ID " + i + "','NAME " + i + "','PHONE " + i
+ "']}";
if (i != pageSize + index - 1 && i != totalRecord - 1) {
json += ",";
}
}
json += "]}";
response.getWriter().write(json); // 將JSON數據返回頁面
} catch (Exception ex) {
}
}
}
目錄結構:
展現的效果:
http://blog.csdn.net/polaris1119/archive/2010/01/04/5130974.aspx
http://d.download.csdn.net/down/1142295/ctfzh
http://hi.baidu.com/fangle_life/blog/item/1076b6fa85a9ba1c6d22eb1e.html
http://blog.csdn.net/polaris1119/archive/2010/01/12/5183327.aspx