`
tanlingcau
  • 浏览: 138283 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

jqGrid:六、 search

阅读更多
页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>grid.html</title>
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3" />
        <meta http-equiv="description" content="this is my page" />
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

        <link rel="stylesheet" type="text/css" media="screen"
            href="css/themes/redmond/jquery-ui-1.8.2.custom.css" />
        <link rel="stylesheet" type="text/css" media="screen"
            href="css/themes/ui.jqgrid.css" />
        <link rel="stylesheet" type="text/css" media="screen"
            href="css/themes/ui.multiselect.css" />
        <link rel="stylesheet" type="text/css" media="screen"
            href="css/themes/jquery.searchFilter.css" />
        <style>
html,body { -
    -margin: 0; /* Remove body margin/padding */
    padding: 0;
    overflow: hidden; /* Remove scroll bars on browser window */
    font-size: 75%;
}
</style>

        <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
        <script src="js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
        <script src="js/src/ui.multiselect.js" type="text/javascript"></script>
        <script src="js/src/grid.loader.js" type="text/javascript"></script>
        <script type="text/javascript">
            $.jgrid.no_legacy_api = true;
            $.jgrid.useJSON = true;
        </script>
        <script type="text/javascript">
            $(function(){ 
              $("#grid_id").jqGrid({
                url:'/demo2/servlet/JqGridJsonServlet',
                mtype: 'GET',
                datatype: 'json',
                jsonReader : {
                    id: "invId",//the unique id of the row.如果不设置则默认为行号.
                    repeatitems: false
                    //element tells jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell element. Setting this option to false instructs jqGrid to search elements in the json data by name. This is the name from colModel or the name described with the jsonmap option in colModel.
                    //A very useful feature here is that there is no need to include all the data that is represented in colModel. Since we make a search by name, the order does not need to match the order in colModel.
                    //设置为false,则可以在json串中根据列/值为传数据,并且列/值在json串中的位置可以随意,也可以不传。 
                },
                height: "auto",
                loadui: "disable",
                colNames:['Inv No','Date', 'ClientId', 'Amount','Tax','Total','Notes'],
                colModel :[ 
                  {name:'invId', index:'invId', width:70, search:false}, 
                  //name:Set the unique name in the grid for the column. This property is required. As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn.
                  //index:Set the index name when sorting. Passed as sidx parameter.index是后台排序时使用。
                  //search:Determines if the field can be searched.是否可以作为搜索条件
                  {name:'invDate', index:'invDate', width:120, editable:true, search:false}, 
                  {name:'client_Id', index:'client_Id', width:120, editable:true}, 
                  {name:'amount', index:'amount', width:90, align:'right', editable:true}, 
                  {name:'tax', index:'tax', width:90, align:'right', editable:true}, 
                  {name:'total', index:'total', width:90, align:'right', editable:true}, 
                  {name:'note', index:'note', width:180, sortable:false, editable:true, search:false} 
                ],
                pager: '#pager',
                rowNum:10,
                rowList:[10,20,30],
                sortname: 'invid',
                sortorder: 'asc',
                viewrecords: true,
                caption: 'My first grid'
              });
              //jQuery("#grid_id").jqGrid('navGrid','#pager',{parameters},prmEdit, prmAdd, prmDel, prmSearch, prmView)
              jQuery("#grid_id").jqGrid('navGrid','#pager',{add:true,edit:true,view:true,del:true,search:true,refresh:true},
                  {url:'/demo2/servlet/JqGridJsonServlet',closeAfterEdit:true, closeOnEscape:true, left:240}, // settings for edit
                {url:'/demo2/servlet/JqGridJsonServlet',closeAfterAdd:true, closeOnEscape:true, left:240}, // settings for add
                {url:'/demo2/servlet/JqGridJsonServlet',closeAfterEdit:true, closeOnEscape:true, top:90, left:240, resize:false, drag:false},  // settings for del
                {url:'/demo2/servlet/JqGridJsonServlet',multipleSearch:true, closeAfterSearch:true, closeOnEscape:true, sopt:['le','ge']}, // enable the advanced searching
                {closeOnEscape:true, left:240} // allow the view dialog to be closed when user press ESC key
              );
            }); 
        </script>
    </head>
    <body>
        <table id="grid_id"></table>
        <div id="pager"></div>
    </body>
</html>

servlet
package com.qoma.servlet;

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

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

import org.apache.commons.lang.StringUtils;

import com.et.ar.exception.ActiveRecordException;
import com.qoma.db.vo.InvHeader;
import com.qoma.service.InvHeaderService;
import com.qoma.util.Json;

public class JqGridJsonServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1676458940650461673L;

    private InvHeaderService service = new InvHeaderService();
    private InvHeader vo;

    private String search;// 是否为搜索
    private String filters;// 搜索值
    private String searchField;
    private String searchOper;
    private String searchString;

    private Integer page;// 当前页
    private Integer rows;// 每页记录数
    private String sidx;// 排序列
    private String sord;// 排序为正序倒序
    private String oper;// 数据操作

    private String s;// 返回值

    private Long count;// 总记录数
    private Integer totalPages;// 总页数
    private Integer start;// 开始位置

    /**
     * Constructor of the object.
     */
    public JqGridJsonServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        this.initParameter(request);

        if ("true".equals(search)) {// 搜索
            if (StringUtils.isEmpty(filters)) {// 单条件搜索
                this.pageCount();
                try {
                    List<InvHeader> list = service.getLimitList(start, rows, sidx, sord, searchField, searchString, searchOper);
                    s = service.getAllJson(page, totalPages, count, list);
                } catch (ActiveRecordException e) {
                    e.printStackTrace();
                    s = Json.FAILURE;
                }
            } else {// 多重搜索
                //filters = {"groupOp":"AND","rules":[{"field":"client_Id","op":"eq","data":"2"},{"field":"tax","op":"ne","data":"4"}]}
            }
        } else {
            if (StringUtils.isEmpty(oper)) {// 查询操作
                this.pageCount();
                try {
                    List<InvHeader> list = service.getLimitList(start, rows, sidx, sord);
                    s = service.getAllJson(page, totalPages, count, list);
                } catch (ActiveRecordException e) {
                    e.printStackTrace();
                    s = Json.FAILURE;
                }
            } else {// 增删改操作
                if ("del".equals(oper)) {
                    try {
                        service.deleteInvHeader(vo);
                        s = Json.SUCCESS;
                    } catch (ActiveRecordException e) {
                        e.printStackTrace();
                        s = Json.getFailure(e.getMessage());
                    }
                } else {
                    if ("add".equals(oper)) {
                        try {
                            if (service.addInvHeader(vo)) {
                                s = Json.SUCCESS;
                            } else {
                                s = Json.FAILURE;
                            }
                        } catch (ActiveRecordException e) {
                            e.printStackTrace();
                            s = Json.getFailure(e.getMessage());
                        }
                    } else if ("edit".equals(oper)) {
                        try {
                            if (service.updateInvHeader(vo)) {
                                s = Json.SUCCESS;
                            } else {
                                s = Json.FAILURE;
                            }
                        } catch (ActiveRecordException e) {
                            e.printStackTrace();
                            s = Json.getFailure(e.getMessage());
                        }
                    }
                }
            }
        }

        out.println(s);
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     * 
     * @throws ServletException
     *             if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

    private void initParameter(HttpServletRequest request) {
        search = request.getParameter("_search");
        filters = request.getParameter("filters");
        searchField = request.getParameter("searchField");
        searchOper = request.getParameter("searchOper");
        searchString = request.getParameter("searchString");

        oper = request.getParameter("oper");
        String pageValue = request.getParameter("page");
        page = StringUtils.isEmpty(pageValue) ? 0 : Integer.parseInt(pageValue);
        String rowsValue = request.getParameter("rows");
        rows = StringUtils.isEmpty(rowsValue) ? 0 : Integer.parseInt(rowsValue);
        sidx = request.getParameter("sidx");
        sord = request.getParameter("sord");

        String idValue = request.getParameter("id");
        Integer invId = (StringUtils.isEmpty(idValue) || "_empty".equals(idValue)) ? 0 : Integer.parseInt(idValue);// add操作时,id值默认为_empty
        String invDateValue = request.getParameter("invDate");
        String clientIdValue = request.getParameter("client_Id");
        String amountValue = request.getParameter("amount");
        String taxValue = request.getParameter("tax");
        String totalValue = request.getParameter("total");
        String noteValue = request.getParameter("note");

        vo = new InvHeader();
        vo.invId = invId;
        vo.invDate = invDateValue;
        vo.client_Id = StringUtils.isEmpty(clientIdValue) ? 0 : Integer.parseInt(clientIdValue);
        vo.amount = StringUtils.isEmpty(amountValue) ? 0 : Float.parseFloat(amountValue);
        vo.tax = StringUtils.isEmpty(taxValue) ? 0 : Float.parseFloat(taxValue);
        vo.total = StringUtils.isEmpty(totalValue) ? 0 : Float.parseFloat(totalValue);
        vo.note = noteValue;
    }

    private void pageCount() {
        if (StringUtils.isEmpty(searchField) || StringUtils.isEmpty(searchString) || StringUtils.isEmpty(searchOper)) {
            try {
                count = service.getCount();
            } catch (ActiveRecordException e) {
                e.printStackTrace();
            }
        } else {
            try {
                count = service.getCount(searchField, searchString, searchOper);
            } catch (ActiveRecordException e) {
                e.printStackTrace();
            }
        }
        
        if (null == sidx || "".equals(sidx))
            sidx = "1";

        if (count > 0 && rows > 0) {
            totalPages = new Long(count / rows).intValue();
            if (count % rows != 0) {
                totalPages += 1;
            }
        } else {
            totalPages = 0;
        }

        // if for some reasons the requested page is greater than the
        // total
        // set the requested page to total page
        if (page > totalPages)
            page = totalPages;

        // calculate the starting position of the rows
        start = rows * page - rows;

        if (start < 0)
            start = 0;

    }

}
分享到:
评论

相关推荐

    jqGrid:四、 remote data(JSON)

    对于搜索,可以使用`search`、`filters`或`searching`选项来实现。 ### 示例代码 以下是一个使用jqGrid加载远程JSON数据的完整示例: ```html &lt;!DOCTYPE html&gt; &lt;link rel="stylesheet" href="https://cdnjs....

    jqgrid实现分组显示和统计

    searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'] }, formatter: 'number', formatoptions: { decimalPlaces: 2 }, custom_func: function (cellval, options, record) { ...

    jqgrid 编辑表格 一列

    $("#grid").jqGrid('navGrid', '#gridpager', { edit: true, add: true, del: true, search: true }); $("#grid").jqGrid('navButtonAdd', '#gridpager', { caption: "Edit", buttonicon: "ui-icon-pencil", ...

    jqGrid使用demo: 数据加载 增加, 修改, 删除, 还原, 撤销等

    数据加载过程中,还可以配置分页、排序和搜索等功能,如`loadonce`(一次性加载所有数据)、`sortname`(默认排序列)和`search`(开启搜索)等选项。 二、增加数据 在jqGrid中,新增数据通常通过弹出对话框进行。...

    关于jqGrid中查询功能

    当用户触发查询操作时,jqGrid会以POST方式向服务器发送请求,携带两个关键参数:“_search”和“filters”。其中,“_search”的值为“true”表明这是一个查询请求,而“filters”则包含了具体的查询条件。 ...

    jqGrid练习示例

    这需要配置`search`和`filters`选项,并可能需要自定义搜索规则。 8. **编辑与添加记录**:jqGrid支持行内编辑和弹出式编辑模式,通过`editRow`和`addRowData`方法实现。同时,还可以配置编辑和保存按钮。 9. **...

    jqgrid4.0包

    用户可以自定义筛选条件,并通过 `search` 和 `filterToolbar` 方法启用搜索栏。 7. **国际化**:jqGrid 支持多语言,通过 `locale` 参数可以切换不同的语言环境,提供更友好的用户体验。 8. **样式和主题**:...

    jqgrid ace 使用手册 技巧

    你可以通过`pager`选项设置分页栏,通过`sortname`和`sortorder`设置初始排序,通过`colModel`中的`search`属性启用列过滤。 6. **编辑与添加**:jqGrid支持行内编辑和弹出式编辑模式,可以通过`inline editing`或`...

    jqgrid入门案例

    $("#grid").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true, search: true }); ``` ### 6. 自定义主题 jqGrid支持主题切换,通过改变CSS引用可以轻松改变界面风格。例如,要切换到Bootstrap UI...

    JQGrid 入门案例

    viewicon: 'ui-icon ui-icon-search' } } ] ``` ### 7. 事件处理 JQGrid提供了丰富的事件接口,如`onSelectRow`、`beforeSelectRow`等,可以监听用户的各种操作,实现自定义逻辑。 通过以上步骤,我们可以构建...

    jqgrid 表格的增删改查以及modal弹出框

    **查询(Search)**:jqGrid 支持多种搜索选项,如基本搜索、高级搜索和过滤。用户可以通过设置列的可搜索属性,然后使用内置的搜索工具栏或下拉菜单来筛选数据。在“RuanTai.Finance”项目中,可能已经配置了这些...

    jqGrid 4.1 示例(二)

    $("#grid").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true, search: false }); ``` 在WCF服务端,我们需要创建一个处理JSON数据的接口。WCF支持多种绑定和数据协定,JSON支持可以通过使用`...

    jqGrid教程

    3. 搜索:使用`search`和`filter`选项,可以实现高级搜索功能,包括模糊匹配和组合条件筛选。 五、编辑与操作 jqGrid支持行内编辑、弹出式编辑和添加、删除、保存操作。通过`editGridRow`和`delGridRow`等方法,...

    jqgrid很全的资料

    search: true, stype: 'text', searchoptions: { dataInit: datePick, attr: { title: 'SelectDate' } } } ] }); // 定义 datePick 函数 datePick = function (elem) { jQuery(elem).datepicker(); } ``` ...

    Jquery_jqGrid 帮助文档

    {name: 'ModifiedDate', index: 'ModifiedDate', width: 150, align: "center", search: false} ], rowList: [10, 20, 30], // 每页显示行数 sortname: 'SalesReasonID', // 默认排序字段 viewrecords: true, /...

    jqGrid搜索

    jqGrid是一款基于jQuery的开源数据网格插件,用于在网页上展示和操作大量结构化的数据。它提供了丰富的功能,如分页、排序、过滤、编辑、添加、删除和搜索等,使得开发者能够轻松构建交互式的表格。在本教程中,我们...

    jQgrid+demo

    直接从官方网站上下载...2 如果遇到Toolbar上 search按钮 放大镜图标 出现布局错误 遮罩把所有内容都遮住了 此时可以尝试将demo文件夹中的 themes目录下的 ui jqgrid css 文件 替换为源码包中的版本 或者替换成 http: ...

    jqGrid-master

    - **Sorting and Filtering**:使用`sortname`和`sortorder`进行默认排序,通过`colModel`中的`search`和`searchrules`定义列的过滤规则。 - **Events**:jqGrid提供了丰富的事件,如`loadComplete`、`...

    jqgrid加载本地数据分页Demo

    通过设置`search`参数为`true`和定义`searching`选项,可以开启内置的搜索功能。 7. **示例代码分析** 在这个"jqgrid本地数据分页"的示例中,我们可以看到一个完整的jqGrid实例,包括数据加载、列定义、分页设置...

Global site tag (gtag.js) - Google Analytics