YUI2.8 实现TabView和DataTable的结合使用

实现的功能:使用YUI2.8 实现TabView和DataTable的结合使用,在TabView添加两个tab,每个tab都是datatable,datatable的数据是从后台动态获取数据,同时实现分页的功能。

 

简述我的调试过程,先做好一个datatable,保证单个datatable能正确地显示,且分页功能没有问题,然后做一个简单的tabview,也同样保证没有问题之后;再完成最后一步的整合功能。

主要的时间是花在写JS脚本和调试上,做事还是一步一步来,遇到问题不要紧张,仔细想想是自己什么地方写错了,或者那个JS CSS文件没有引对。

 

我也是YUI的新手,希望有人能和我互相交流。

 

后台的代码

1、YuiTabAction.java

package com.demo.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.demo.model.Book;
import com.demo.model.InstBean;
import com.demo.yuiutil.JSONResult;
import com.demo.yuiutil.YUIPagination;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("all")
public class YuiTabAction extends BaseStruts2Action{
	public void getBookList(){
		System.out.println(" getBookList is called....startIndex="+startIndex);
		List<Book> bookList = new ArrayList<Book>();
		recordsReturned = 10;
		for(int i=1; i<10; i++){
			Book book = new Book();
			book.setId(startIndex+i);
			book.setAmount(startIndex+i+10);
			book.setQuantity(startIndex+i+100);
			book.setTitle("title("+startIndex+i+")");
			bookList.add(book);
		}
		pageSize = 10;
		totalRecords = 20;//假设总记录数是20条,
		YUIPagination yuiPage = new YUIPagination();
		yuiPage.setRecordsReturned(recordsReturned);
		yuiPage.setTotalRecords(totalRecords);
		yuiPage.setStartIndex(startIndex);
		yuiPage.setPageSize(pageSize);
		yuiPage.setSort("ASC");
		yuiPage.setRecords(bookList);		
		this.outJson(yuiPage);	
	}
	
	public void getInstList(){
		System.out.println(" getInstList is called....startIndex="+startIndex);
		List<InstBean> bookList = new ArrayList<InstBean>();
		recordsReturned = 10;
		for(int i=1; i<10; i++){
			InstBean bean = new InstBean();
			bean.setPtInsId(startIndex+i);
			bean.setPtInsName("instName"+(startIndex+i+10));
			bean.setPtInsDesc("desc("+startIndex+i+")");
			bookList.add(bean);
		}
		pageSize = 10;
		totalRecords = 20;//假设总记录数是20条,
		YUIPagination yuiPage = new YUIPagination();
		yuiPage.setRecordsReturned(recordsReturned);
		yuiPage.setTotalRecords(totalRecords);
		yuiPage.setStartIndex(startIndex);
		yuiPage.setPageSize(pageSize);
		yuiPage.setSort("ASC");
		yuiPage.setRecords(bookList);		
		this.outJson(yuiPage);	
	}
}

 

2、struts.xml

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<include file="struts-default.xml"/>
	<constant name="struts.objectFactory" value="spring" />
	<package name="yuitab" namespace="/yuitab" extends="struts-default">
		<action name="do_*" method="{1}" class="com.demo.action.YuiTabAction">
		</action>
	</package>
</struts>

 

前台的代码:

 1、/yuiapp/WebRoot/pages/tabview/tabview01.jsp

 

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%String sysPath =basePath+"appjs/yuijs/build"; %>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>tabview_01</title>
<style type="text/css">
body {
	margin:0;
	padding:0;
}
</style>

<link rel="stylesheet" type="text/css" href="<%=sysPath%>/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="<%=sysPath%>/tabview/assets/skins/sam/tabview.css" />
<link rel="stylesheet" type="text/css" href="<%=sysPath%>/datatable/assets/skins/sam/datatable.css" />
<link rel="stylesheet" type="text/css" href="<%=sysPath %>/paginator/assets/skins/sam/paginator.css" />
<link rel="stylesheet" type="text/css" href="<%=sysPath %>/container/assets/skins/sam/container.css" />

<script type="text/javascript" src="<%=sysPath%>/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="<%=sysPath%>/container/container-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/element/element-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/tabview/tabview-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/datasource/datasource-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/datatable/datatable-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/connection/connection-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/json/json-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/paginator/paginator-min.js"></script>
<script type="text/javascript" src="<%=sysPath%>/dragdrop/dragdrop-min.js"></script>

</head>
<body class="yui-skin-sam">
<div id="tabviewId" class="yui-navset">
    <ul class="yui-nav">
        <li class="selected"><a href="#tab2"><em>DataTable Tab</em></a></li>
        <li><a href="#tab3"><em>Another Tab</em></a></li>
 
    </ul>            
    <div class="yui-content">
        <div id="bookDTId"></div>
        <div id="instDTId"></div>
    </div>
</div>


<script type="text/javascript">
YAHOO.example.TabViewApp = function() { 
    var bookColumn = [
            {key:"id"},
            {key:"quantity"},
            {key:"amount"},
            {key:"title"}
    ];
    var bookDS = new YAHOO.util.DataSource("/yuitab/do_getBookList.action?");
    bookDS.responseType = YAHOO.util.DataSource.TYPE_JSON;
    bookDS.responseSchema = {
        resultsList: "records",
        fields: [
            {key:"id"},
            {key:"quantity"},
            {key:"amount"},
            {key:"title"}           
        ],
        metaFields: {
            totalRecords: "totalRecords" // Access to value in the server response
        }
    };
    
    // DataTable configuration
    var bookCfg = {
        initialRequest: "pageSize=10&sort=id&dir=asc&startIndex=0",// Initial request for first page of data
        dynamicData: true, // Enables dynamic server-driven data
        paginationEventHandler : YAHOO.widget.DataTable.handleDataSourcePagination, 
        sortedBy : {key:"id", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
        paginator: new YAHOO.widget.Paginator(
                {   rowsPerPage:10,
                	firstPageLinkLabel : "首页",   
	                lastPageLinkLabel : "末页",   
	                previousPageLinkLabel:"上页",  
	                nextPageLinkLabel:"下页"  
		          }) // Enables pagination 
    };
    
    // DataTable instance
    var bookDT = new YAHOO.widget.DataTable("bookDTId", bookColumn, bookDS, bookCfg);
    // Update totalRecords on the fly with value from server
    bookDT.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
        oPayload.totalRecords = oResponse.meta.totalRecords;
        return oPayload;
    };      
    
    /** ========================================================================   **/
    var instColumn = [
            {key:"ptInsId"},
            {key:"ptInsName"},
            {key:"ptInsDesc"}
    ];
    var instDS = new YAHOO.util.DataSource("/yuitab/do_getInstList.action?");
    instDS.responseType = YAHOO.util.DataSource.TYPE_JSON;
    instDS.responseSchema = {
        resultsList: "records",
        fields: [
            {key:"ptInsId"},
            {key:"ptInsName"},
            {key:"ptInsDesc"}       
        ],
        metaFields: {
            totalRecords: "totalRecords" // Access to value in the server response
        }
    };
    
    // DataTable configuration
    var instCfg = {
        initialRequest: "pageSize=10&sort=ptInsId&dir=asc&startIndex=0", // Initial request for first page of data
        dynamicData: true, // Enables dynamic server-driven data
        paginationEventHandler : YAHOO.widget.DataTable.handleDataSourcePagination, 
        sortedBy : {key:"ptInsId", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
        paginator: new YAHOO.widget.Paginator(
                {   rowsPerPage:10,
                	firstPageLinkLabel : "首页",   
	                lastPageLinkLabel : "末页",   
	                previousPageLinkLabel:"上页",  
	                nextPageLinkLabel:"下页"  
		          }) // Enables pagination 
    };
    
    // DataTable instance
    var instDT = new YAHOO.widget.DataTable("instDTId", instColumn, instDS, instCfg);
    // Update totalRecords on the fly with value from server
    instDT.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
        oPayload.totalRecords = oResponse.meta.totalRecords;
        return oPayload;
    };        
    
    var myTabView = new YAHOO.widget.TabView("tabviewId");
    var responseSuccess = function(o){
   		alert("inner responseSuccess is called;o.argument="+o.argument+";o.responseText="+o.responseText);
    };
    var responseFailure = function(o){ 
       alert("inner 服务器处理失败 : " + o.statusText);
    }
   
    var callback = {   
        success :responseSuccess,   
        failure :responseFailure,   
        argument : null  
    };
   
    myTabView.getTab(0).addListener("click", function() {
       alert("tab(0) is click...... ");
       var urlStr ="/yuitab/do_getBookList.action?type=new&pageSize=10&sort=id&dir=asc&startIndex=0";
       bookDS.sendRequest(urlStr,callback,bookDT);   
       bookDT.onShow();
       
     });  
	myTabView.getTab(1).addListener("click", function() {
		 alert("tab(1) is click...... ");
		 var urlStr ="/yuitab/do_getInstList.action?type=new&pageSize=10&sort=id&dir=asc&startIndex=0";
         instDS.sendRequest(urlStr,callback,instDT);  
		 instDT.onShow();
    }); 
   
   
    /*return { //这段返回值可以注释掉,也没有用!
        oDS: bookDS,
        oDT: bookDT,
        oTV: myTabView
    };*/
}();

</script>
</body>
</html>

 

 

 

 

你可能感兴趣的:(JavaScript,json,struts,css,Yahoo)