2010-10-31 33 views
19

我有一個這樣的形式:我的jqGrid的jqGrid:POST數據到服務器以抓取行數據(過濾和搜索)

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

和表:

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

我需要張貼(不是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" 
    } 
}); 

你可以看到我做錯了什麼或應該做不同?

回答

39

你的主要錯誤是postData參數的形式使用:

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

這種用法有兩個問題:

  1. $("#myForm").serialize()覆蓋POST請求的所有參數,而不是增加額外的參數。
  2. $("#myForm").serialize()將計算只在網格初始化時間一次。所以你總是會發送search=""maxPrice=""到服務器。

我建議你到一個名爲編輯字段替換形式

<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"}); 

它或許可以代替你使用搜索形式。

+1

@Byron Sommardahl:你一週以來沒有對我的回答發表評論。你讀了我的答案嗎?它可以幫助你嗎?你的問題已經解決了嗎? – Oleg 2010-11-08 13:11:43

+2

來自@Oleg的另一個令人敬畏的答案。 – 2012-06-25 19:03:55

+0

@AJ .:我很高興舊的答案仍然有幫助。 – Oleg 2012-06-25 19:58:09

相關問題