数据加载中……
YUI-dataTable 服务端分页及动态排序
今天先讲下YUI的数据表格中,从服务端获取数据和根据服务端数据排序的方法.官方示例的地址:http://developer.yahoo.com/yui/examples/datatable/dt_dynamicdata.html

首先是必备的js,css文件的引入,可以从以下地址配置:http://developer.yahoo.com/yui/articles/hosting/?datatable#configure

服务端返回数据的格式(=.=! 暂时还没找到改变这种格式的其他方法,应该是跟数据源有关):
{"recordsReturned":25,
    
"totalRecords":1397,
    
"startIndex":0,
    
"sort":null,
    
"dir":"asc",
    
"pageSize":10,
    
"records":[
        {
"id":"0",
        
"name":"xmlqoyzgmykrphvyiz",
        
"date":"13-Sep-2002",
        
"price":"8370",
        
"number":"8056",
        
"address":"qdfbc",
        
"company":"taufrid",
        
"desc":"pppzhfhcdqcvbirw",
        
"age":"5512",
        
"title":"zticbcd",
        
"phone":"hvdkltabshgakjqmfrvxo",
        
"email":"eodnqepua",
        
"zip":"eodnqepua",
        
"country":"pdibxicpqipbsgnxyjumsza"},
        
    ]
}

JS代码:
中间会穿插些struts2的标签
YAHOO.namespace('YAHOO.uunav');
$(document).ready(
function(){  //YUI的LOAD方法写起来没有JQUERY的简单,呵呵,偷下懒,结合起来用
var table = YAHOO.yayasoft.buildTable({
                url:
"${contextPath}/ajax/phone!initPhone.act?",
                param:
"sort=id&dir=desc&startIndex=0&pageSize=<s:property value='pages.pageSize' />",
                pageSize:
<s:property value='pages.pageSize' />
            });
}
//构建一个表格,数据通过datasource获取,服务器以JSON格式返回数据
        YAHOO.uunav.buildTable=function(config){
            
var Dom = YAHOO.util.Dom;  //定义一个DOM对象 
            //定义表格列,key:数据字段,label:页面显示名称,sortable:是否排序,默认false
            var myColumnDefs = [
                {key:
"id",label:"编号",sortable:true},
                {key:
"company",label:"公司名称",sortable:true},
                {key:
"tel1",label:"电话号码",sortable:true},
                {key:
"privinceStr",label:"省份"},
                {key:
"cityStr",label:"城市"},
                {key:
"ischeck",label:"审核情况",sortable:true},
                {key:
"catalog.names",label:"类别"},
                {key:
"createDate",label:"创建日期",sortable:true},
                {key:
"coment",label:"评论",formatter:"myComent"}
                
//{key:"ac",label:"操作",formatter:"myAction"}
                //{key:"ac",label:"操作"}
            ];
            
            
//格式化表格
            YAHOO.widget.DataTable.Formatter.myComent = function(elCell, oRecord, oColumn, oData){
                
//var d=oData
                //if(YAHOO.lang.isString(oData)){
                //    elCell.innerHTML="string"+oData.length;
                //
                if(oData.length>5){
                    elCell.innerHTML
=oData.substring(0,5)+"";
                }
else{
                    elCell.innerHTML
=oData;
                }
                elCell.title
=oData;
            }
            
            YAHOO.widget.DataTable.Formatter.myAction 
= function(elCell, oRecord, oColumn, oData){
                
var id=oRecord.getData("id");
                elCell.innerHTML
="<a href=\"#"+id+"\" >edit</a>";
            }
            
            
//自定义转换函数 用于表格数据展示不同效果 
            var ischecked=function(odata){
                
if(!YAHOO.lang.isNumber(odata)) return  "数据有错误";
                
if(odata==0return "未审核";  //此处由cfg4u配置输出
                if(odata==1return "已审核";
                
if(odata==2return "拒绝";
                
return "数据有错误";
            }
            
             
//格式化日期,因为服务器端获取的日期格式是10位整形
            var formatDate=function(odata){ 
                formatDate.re
=new Date(parseFloat(odata)*parseFloat(1000));
                
return formatDate.re.getYear()+"-"+(formatDate.re.getMonth()+1)+"-"+formatDate.re.getDate();
            }

            
//表格行格式化,elTr:一行,oRecord:数据
            var myRowFormatter=function(elTr, oRecord){
                
if(oRecord.getData('ischeck')=='未审核' || oRecord.getData('tel1')==""){
                    Dom.addClass(elTr,'mark');
                }
                
return true;
            }

            
//设置数据源,数据最终会提供给表格处理
            var myDataSource = new YAHOO.util.DataSource(config.url);
            myDataSource.responseType 
= YAHOO.util.DataSource.TYPE_JSON;
            myDataSource.responseSchema 
= {
                resultsList:
"records",  //服务端返回的数据
                fields:[  //配置数据列,格式化数据
                    {key:"id", parser:"number"},
                    {key:
"uucallId", parser:"number"},
                    {key:
"uucallName"},
                    {key:
"privince"},
                    {key:
"city"},
                    {key:
"company"},
                    {key:
"address"},
                    {key:
"tel1"},
                    {key:
"grad"},
                    {key:
"coment"},
                    {key:
"ip"},
                    {key:
"ischeck", parser:ischecked},  //自定义格式化方法ischecked
                    {key:"createDate", parser:formatDate},
                    {key:
"privinceStr"},
                    {key:
"cityStr"},
                    {key:
"catalog.names"}
                    
//{key:"ac"}
                ],
                metaFields:{
                    totalRecords:
"totalRecords"
                }
            }
            
            
var pagnav=new YAHOO.widget.Paginator({
                containers:
"pagnav",
                rowsPerPage:config.pageSize,
                firstPageLinkLabel:
"首页",
                lastPageLinkLabel:
"末页",
                nextPageLinkLabel:
"下一页",
                previousPageLinkLabel:
"上一页"
            });
            
            
//表格配置,initialRequest:初始的URL参数,用于分页的参数,dynamicData:是否动态获取数据,sortedBy:排序{key:排序字段,dir:升序:CLASS_ASC,降序:CLASS_DESC}
            var myConfigs = {
                initialRequest:config.param,
                dynamicData:
true,
                sortedBy:{key:
"id",dir:YAHOO.widget.DataTable.CLASS_DESC},
                paginator:pagnav 
//分页导航,这里可以通过Paginator对象配置导航样式
                //formatRow: myRowFormatter
                //scrollable:true,
                //width:"80%"
            };
            
            
//创建一个带数据的表格.参数:(表格输出位置,列配置,数据源,表格配置)
            var myDataTable = new YAHOO.widget.DataTable("phoneTable",myColumnDefs, myDataSource, myConfigs);
            myDataTable.handleDataReturnPayload 
= function(oRequest,oResponse,oPayload){  //动态获取totalRecords,分页用
                oPayload.totalRecords = oResponse.meta.totalRecords;
                
return oPayload;
            }
            
            
//高亮行,鼠标移过时高亮作用
            myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
            myDataTable.subscribe(
"rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
            myDataTable.subscribe(
"rowClickEvent", myDataTable.onEventSelectRow); //标准行选择,支持多行选择
            
            
//myDataTable.subscribe("rowClickEvent", function(){myDataTable.getSelectedRows;});
             
            
return {
                ds:myDataSource,
                dt:myDataTable
            };
        }
//给表格添加右健菜单,用于操作
        YAHOO.uunav.buildMenu = function(){
            
//add context menu to table
            var onContextMenuClick = function(p_sType,p_aArgs,p_myDataTable){
                
var task = p_aArgs[1];
                
//alert(1);
                    
                
if(task){
                    
var elRow = this.contextEventTarget;
                    elRow 
= p_myDataTable.getTrEl(elRow);
                    
var oRecord=p_myDataTable.getRecord(elRow);
                    
if(elRow){
                        
switch(task.index){
                            
case 0:
                                tb_show('添加号码信息','${contextPath}
/mng/phone!adminit.act?width=450&height=220','false');
                                
break;
                            
case 1:
                                
//alert("edit"+oRecord.getData("id"));
                                tb_show('修改-'+oRecord.getData("company"),'${contextPath}/mng/phone!adminit.act?width=450&height=220&form.id='+oRecord.getData("id"),'false'); 
                                
break;
                            
case 2:
                                
if(confirm("您确定要删除这些记录吗?")){  //oRecord.getData("id")
                                    $.ajax({
                                        type:
"POST",
                                        url:
"${contextPath }/ajax/phone!del.act",
                                        data:
"form.id="+oRecord.getData("id"),
                                        dataType:
"json",
                                        success:
function(data){
                                            
if(data.message.result){
                                                p_myDataTable.deleteRow(elRow);
//先删服务器信息,成功后再删表格信息
                                            }
                                        }
                                    });
                                }
                                
break;
                            
case 3:
                                alert(
"UUNAV Administrator - V1.0");
                        }
                    }
                }
            }
            
            
//右健菜单
            var myContextMenu = new YAHOO.widget.ContextMenu("mycontextmenu",
                {trigger: table.dt.getTbodyEl()});
            myContextMenu.addItem(
"添加");
            myContextMenu.addItem(
"修改");
            myContextMenu.addItem(
"删除");
            myContextMenu.addItem(
"关于");
            myContextMenu.render(
"contextMenu");
            
            myContextMenu.clickEvent.subscribe(onContextMenuClick, table.dt);
            
return myContextMenu;
        }

代码中加了注释,可能看起来仍然有些吃力,建议边做边看.这样效果好.

官方API:http://developer.yahoo.com/yui/docs/module_datatable.html

posted on 2009-02-07 21:25 菜板 阅读(2952) 评论(2)  编辑  收藏 所属分类: YUI

评论

# re: YUI-dataTable 服务端分页及动态排序 2011-08-15 10:39 jjk

查询怎么实现的呀,
app.myDataTable.load(app.myConfigs,app.generateRequest,function(data){
alert("jjk");
app.sqlWhere = "and t.ZGDWBM=? ";
app.values = new Array();
app.values[app.values.length]=app.ZGDWBM;
},app.myDataSource);
这个怎么改啊,有例子吗?
  回复  更多评论    

# re: YUI-dataTable 服务端分页及动态排序 2013-09-09 16:48 wk

我的代码总是在{trigger: table.dt.getTbodyEl()});就断了
  回复  更多评论    

只有注册用户登录后才能发表评论。


网站导航: