zoukankan      html  css  js  c++  java
  • jqGrid(2)

    jqGrid使用方法:

    原文地址:http://blog.csdn.net/y0ungroc/article/details/12008879

    1. 下载文件

    1.     下载jqGrid的软件包,目前最新版本为4.4.1 下载地址为: http://www.trirand.com/blog/?page_id=6

    2.     下载jQuery文件,目前最新版本为1.8.2 下载地址为: http://code.jquery.com/jquery-1.8.2.min.js

    3.     下载jqGrid皮肤,下载地址为: http://jqueryui.com/themeroller/  

    2. 准备文件

    在项目的根目录下,建立相应的文件夹,放入下载的文件,目录结构如下图:

    捕获

    3. 页面中得代码
    3.1、head中加入引用
    ·        css文件引入:
    <link type="text/css" rel="stylesheet" href="jqGrid/themes/cupertino/jquery-ui-1.9.0.custom.min.css">
    <link type="text/css" rel="stylesheet" href="jqGrid/themes/ui.jqgrid.css">
    ·        js文件引入:
    <script type="text/javascript" src="jquery-1.8.2.min.js" />
    <script type="text/javascript" src="jqGrid/js/jquery-ui-1.9.0.custom.min.js"/>
    <script type="text/javascript" src="jqGrid/js/i18n/grid.locale-cn.js"/>
    <script type="text/javascript" src="jqGrid/js/jquery.jqGrid.min.js"/>
    3.2、body中的代码
    <table id="list4"></table>
    <div id="gridPager"></div>

    其中,list4为列表jqGrid,gridPager为列表的分页div

    3.3、js中的代码
    $(document).ready(function(){
        $("#list4").jqGrid({
            url:'/Home/GridData',
            datatype:"json", //数据来源,本地数据
            mtype:"POST",//提交方式
            height:420,//高度,表格高度。可为数值、百分比或'auto'
            //1000,//这个宽度不能为百分比
            autotrue,//自动宽
            colNames:['订单号','客户编号','客户姓名','客户地址'],

                 colModel:[
                     {name:'OrderID',index:'OrderID',100,align:'left'},
                     {name:'UserID',index:'UserID',100,align:'left'},
                     {name:'Name',index:'Name',100,align:'left'},
                     {name:'Address',index:'Address',200,align:'left'}

                   ],

            rownumbers:true,//添加左侧行号
            //altRows:true,//设置为交替行表格,默认为false

                  sortName:'OrderID',
                  sortorder:'desc',

            viewrecords: true,//是否在浏览导航栏显示记录总数
            rowNum:15,//每页显示记录数
            rowList:[15,20,25],//用于改变显示行数的下拉列表框的元素数组。
            pager:$('#gridPager')
        });
    });

    至此,整个使用jqGrid的前端使用就基本完毕了,当加载此页面的时候,将初始化jqGrid表格,并通过url请求数据,返回datatype类型的数据。

    后台代码:

      public ActionResult GridDataShow()      

     {             return View("GridData");         }       

      public JsonResult GridData(string sidx,string sord,int page,int rows)        

     {                                                        

                int pageIndex = Convert.ToInt32(page)-1;           

               int pageSize = rows;            

              int totalRecords = eshop.OrderList.Count();                                 

              int totalpages = (int)Math.Ceiling((float)totalRecords/(float)5);

              var orders = eshop.OrderList.OrderBy(c=>c.OrderID).Skip(pageIndex * pageSize).Take(pageSize);                              

              var jsonData = new {     

                                           total = totalpages,                

                                           page = page,              

                                           records = totalRecords,                

                                          rows = (from order in orders                   

                                                      select new {          

                                                      i=order.OrderID,                      

                                                     cell=new  {                        

                                                                     order.OrderID,                       

                                                                     order.UserID,                        

                                                                     order.Name,                        

                                                                     order.Address                      

                                                                  }                   

                                                     } ).ToArray()            

                  };            

                 return Json(jsonData);                

    }

    JqGird的其他用法:                   

    主要是一些基本操作,特殊的数据显示等。

    1 刷新 jqGrid 数据。

    常用到刷新jqGrid数据的情况是,在用到查询的时候,根据查询条件,请求数据,并刷新jqGrid表格,使用方式如下:

    $("#search_btn").click( function (){ 

    // 此处可以添加对查询数据的合法验证

    var orderId = $("#orderId").val(); 

        $("#list4").jqGrid('setGridParam',{ 

            datatype:'json', 

            postData:{'orderId':orderId}, // 发送数据

            page:1 

        }).trigger("reloadGrid"); // 重新载入

    });

    ① setGridParam用于设置jqGrid的options选项。返回jqGrid对象
    ② datatype为指定发送数据的格式;
    ③ postData为发送请求的数据,以key:value的形式发送,多个参数可以以逗号”,”间隔;
    ④ page为指定查询结果跳转到第一页;
    ⑤ trigger(“reloadGrid”);为重新载入jqGrid表格。

    2 无数据的提示信息。

    当后台返回数据为空时,jqGrid本身的提示信息在右下角,不是很显眼

    loadComplete: function () { // 如果数据不存在,提示信息

    var rowNum = $("#list4").jqGrid('getGridParam','records');

    if (rowNum      if ($("#norecords").html() == null ){

                $("#list4").parent().append("</pre>

    <divid="norecords">没有查询记录!</div>

    <pre>");

            }

            $("#norecords").show();

        } else { // 如果存在记录,则隐藏提示信息。

            $("#norecords").hide();

        }

    }

    ① loadComplete 为jqGrid加载完成,执行的方法;

    ② getGridParam这个方法用来获得jqGrid的选项值。它具有一个可选参数name,name即代表着jqGrid的选项名,如果不传入name参数,则会返回jqGrid整个选项options。例:

    $("#list4").jqGrid('getGridParam','records'); // 获取当前 jqGrid 的总记录数;

    注意:这段代码要加在jqGrid的选项设置Option之间,即:$(“#list4″).jqGrid({});代码之间。且各个option之间加逗号间隔。

    3 显示 jqGrid 统计信息。

    通常统计信息都显示在jqGrid表格最后一行,分页控件之上,如下图:

    代码片段:

    $("#list4").jqGrid({

        ......

        colModel:[

            {name:'productName',index:'productName',align:'center',sortable: false },

            {name:'productAmt',index:'productAmt',align:'center'}

        ],

        footerrow: true , // 分页上添加一行,用于显示统计信息

        ......

        pager:$('#gridPager'),

        gridComplete: function () { // 当表格所有数据都加载完成,处理统计行数据

    var rowNum = $( this ).jqGrid('getGridParam','records');

    if (rowNum > 0){

    var options = {

                    url:"test.action", // 默认是 form 的 action ,如果写的话,会覆盖 from 的 action.

                    dataType:"json", //'xml', 'script', or 'json' ( 接受服务端返回的类型 .)

                    type:"POST",

                    success: function (data){ // 成功后调用方法

                        $("#list4").footerData("set",{productName:"合计",productAmt:data.productAmtSum});

                    }

                };

                $("#searchForm").ajaxSubmit(options);

            }

        }

    });

    详细介绍:

    3.1 jqGrid的options配置; 需要在jqGrid的options中添加如下属性:

    footerrow: true , // 分页上添加一行,用于显示统计信息

    3.2  调用gridComplete方法,当数据加载完成后,处理统计行数据;  3.3 调用jqGrid的footerData方法,为统计行赋值:

    $("#list4").footerData("set",{productName:"合计",productAmt:data.productAmtSum});

    4 jqGrid 的数据格式化。

    jqGrid中对列表cell属性格式化设置主要通过colModel中formatter、formatoptions来设置

    基本用法:

    jQuery("#jqGrid_id").jqGrid({

    ...

       colModel:[

          ...

          {name:'price',index:'price',  formatter:'integer', formatoptions:{thousandsSeparator:','}},

          ...

       ]

    ...

    });

    formatter主要是设置格式化类型(integer、email等以及函数来支持自定义类型),formatoptions用来设置对应formatter的参数,jqGrid中预定义了常见的格式及其options:

    integer

    thousandsSeparator: //千分位分隔符,

    defaulValue

    number

    decimalSeparator, //小数分隔符,如”.”

    thousandsSeparator, //千分位分隔符,如”,”

    decimalPlaces, //小数保留位数

    defaulValue

    currency

    decimalSeparator, //小数分隔符,如”.”

    thousandsSeparator, //千分位分隔符,如”,”

    decimalPlaces, //小数保留位数

    defaulValue,

    prefix //前缀,如加上”$”

    suffix//后缀

    date

    srcformat, //source的本来格式

    newformat //新格式

    email

    没有参数,会在该cell是email加上: mailto:name@domain.com

    showlink

    baseLinkUrl, //在当前cell中加入link的url,如”jq/query.action”

    showAction, //在baseLinkUrl后加入&action=actionName

    addParam, //在baseLinkUrl后加入额外的参数,如”&name=aaaa”

    target,

    idName //默认会在baseLinkUrl后加入,如”.action?id=1″。改如果设置idName=”name”,那么”.action?name=1″。其中取值为当前rowid

    checkbox

    disabled //true/false 默认为true此时的checkbox不能编辑,如当前cell的值是1、0会将1选中

    select

    设置下拉框,没有参数,需要和colModel里的editoptions配合使用

    colModel:[

        {name:'id',    index:'id',     formatter:  customFmatter},

        {name:'name',  index:'name',   formatter: "showlink",formatoptions:{baseLinkUrl:"save.action",idName: "id",addParam:"&name=123"}},

        {name:'price', index:'price',  formatter: "currency", formatoptions:{thousandsSeparator:",",decimalSeparator:".",prefix:"$"}},

        {name:'email', index:'email',  formatter: "email"},

        {name:'amount',index:'amount', formatter: "number", formatoptions:{thousandsSeparator:",", defaulValue:"",decimalPlaces:3}},

        {name:'gender',index:'gender', formatter: "checkbox",formatoptions:{disabled: false }},

        {name:'type',  index:'type',   formatter: "select",editoptions:{value:"0:无效;1:正常;2:未知"}}

    ]

    其中customFmatter声明如下:

    function customFmatter(cellvalue, options,rowObject){

        console.log(cellvalue);

        console.log(options);

        console.log(rowObject);

    return "["+cellvalue+"]";

    };

    在页面显示的效果如下: 

    当然还得支持自定义formatter函数,只需要在formatter:customFmatter设置formatter函数,该函数有三个签名:

    function customFmatter(cellvalue, options,rowObject){ 

    }

    //cellvalue- 当前 cell 的值

    //options- 该 cell 的 options 设置,包括 {rowId, colModel,pos,gid}

    //rowObject- 当前 cell 所在 row 的值,如 { id=1, name="name1",price=123.1, ...}

    当然对于自定义formatter,在修改时需要获取原来的值,这里就提供了unformat函数,这里见官网的例子:

    jQuery("#grid_id").jqGrid({

    ...

       colModel:[

          ...

          {name:'price',index:'price', 60, align:"center", editable: true , formatter:imageFormat,unformat:imageUnFormat},

          ...

       ]

    ...

    }); 

    function imageFormat( cellvalue, options,rowObject ){

    return '</pre>

    <imgsrc="'+cellvalue+'" alt="" />

    <pre>';

    }

    function imageUnFormat( cellvalue, options, cell){

    return $('img', cell).attr('src');

    }

    5 常见错误问题:

    chrome报错:

    Uncaught TypeError: Cannot read property‘integer’ of undefined

    IE报错:

    SCRIPT5007: 无法获取属性“integer”的值: 对象为 null 或未定义
    出现这样的问题,是由于页面没有添加语言文件的引用导致的
    解决办法为:添加语言文件js

    <scripttype="text/javascript"src="js/i18n/grid.locale-cn.js"></script>

  • 相关阅读:
    datagrid
    IntelliJ IDEA for mac 引入js注意事项
    centos7安装并配置svn
    yum使用总结
    安装php
    类视图
    django里面添加静态变量
    Ubuntu16.04安装&创建虚拟环境
    制作dockerfile, 天眼查的镜像、并运行
    dockerfile
  • 原文地址:https://www.cnblogs.com/flyaway100/p/3482196.html
Copyright © 2011-2022 走看看