jqGrid:POST数据到服务器以获取行数据(过滤和搜索)

时间:2010-10-31 15:19:35

标签: jquery jqgrid

我有一个这样的表格:

<form id='myForm'>
<input type='text' name='search' />
<input type='text' name='maxPrice' />
</form>

和我的jqGrid的表:

<table id='myGrid'></table>

我需要POST(不是GET)从myForm到我的服务器方法的数据,以便获取行数据并填充网格。到目前为止,我还没有能够让jqGrid发布任何东西。我仔细检查了我的数据序列化,并正确地序列化我的表单数据。这是我的jqGrid代码:

$("#myGrid").jqGrid({
    url: '/Products/Search") %>',
    postData: $("#myForm").serialize(),
    datatype: "json",
    mtype: 'POST',
    colNames: ['Product Name', 'Price', 'Weight'],
    colModel: [
        { name: 'ProductName', index: 'ProductName', width: 100, align: 'left' },
        { name: 'Price', index: 'Price', width: 50, align: 'left' },
        { name: 'Weight', index: 'Weight', width: 50, align: 'left' }
    ],
    rowNum: 20,
    rowList: [10, 20, 30],
    imgpath: gridimgpath,
    height: 'auto',
    width: '700',
    //pager: $('#pager'),
    sortname: 'ProductName',
    viewrecords: true,
    sortorder: "desc",
    caption: "Products",
    ajaxGridOptions: { contentType: "application/json" },
    headertitles: true,
    sortable: true,
    jsonReader: {
        repeatitems: false,
        root: function(obj) { return obj.Items; },
        page: function(obj) { return obj.CurrentPage; },
        total: function(obj) { return obj.TotalPages; },
        records: function(obj) { return obj.ItemCount; },
        id: "ProductId"
    }
});

你能看到我做错了什么或应该做些什么?

1 个答案:

答案 0 :(得分:42)

您的主要错误是在表单中使用postData参数:

postData: $("#myForm").serialize()

这种用法有两个问题:

  1. $("#myForm").serialize()会覆盖POST请求的所有参数,而不是添加其他参数。
  2. 在网格初始化期间,值$("#myForm").serialize()将仅计算 。因此,您始终会将search=""maxPrice=""发送到服务器。
  3. 我建议您将带有命名编辑字段的表单替换为

    <fieldset>
    <input type='text' id='search' />
    <input type='text' id='maxPrice' />
    <button type='button' id='startSearch'>Search</button>
    </fieldset>
    

    使用方法将postData参数定义为对象:

    postData: {
        search: function() { return $("#search").val(); },
        maxPrice: function() { return $("#maxPrice").val(); },
    },
    

    并将onclick事件处理程序添加到“搜索”按钮(参见上面的HTML片段)

    $("#startSearch").click(function() {
        $("#myGrid").trigger("reloadGrid");
    });
    

    此外,您没有写任何关于您使用的服务器技术的内容。可以进行一些额外的修改,以便能够在服务器端读取参数(例如serializeRowData: function (data) {return JSON.stringify(data);},请参阅thisthis)。我建议你也阅读另一个旧答案:How to filter the jqGrid data NOT using the built in search/filter box

    其他一些小错误,例如'/Products/Search") %>'代替'/ Products / Search'或使用已弃用的参数imgpath(请参阅documentation)并不重要。应该更好地删除align: 'left'等默认列选项。

    还要考虑在网格中使用搜索。例如advance searching

    $("#myGrid").jqGrid('navGrid','#pager',
                        {add:false,edit:false,del:false,search:true,refresh:true},
                        {},{},{},{multipleSearch:true});
    

    以及toolbar searching

    $("#myGrid").jqGrid('filterToolbar',
                        {stringResult:true,searchOnEnter:true,defaultSearch:"cn"});
    

    它可能会替换您使用的搜索表单。