2012-01-12 109 views
2

下面的代碼工作得很好,並獲取所有的數據。我想在數據表中插入一些過濾器字符串(sample_container)。因此,對於給定的sample_app,想要在加載頁面時自動使用某些過濾器字符串(filter1,filter2)爲sample_container數據表進行過濾。有任何想法嗎?Jquery數據表字符串過濾器

$("#sample_container").html("<h2>Sample libs</h2>"); 
$.ajax({ 
      type: "GET", 
      url: "some_url", 
      data: some_data, 
      dataType: 'jsonp', 
      crossDomain: true, 
      async: false, 
      success: function(response) { 
       $("#sample_container").html("<h2>Sample Libraries</h2>"); 
       html = "<table class='datatable'>"; 
       blah blah 
       } 
       html += "</table>"; 
       $("#sample_container").append(html); 
       $("#sample_container .datatable").dataTable({ "bPaginate": false, 
                  "bAutoWidth": false, 
                  "bFilter": false, 
                  "bInfo": false 
       }).columnFilter({ sPlaceHolder: "head:after", 
            aoColumns: [ { type: "text" }, 
               { type: "text" }, 
               { type: "text" } 
            ] 
       }); 
      }, 

     }); 


{% if sample_app %} 
    <h1>{{ sample_app.id }} - {{ sample_app.name }}</h1> 
    <br/> 
    blah blah... 
{% endif %} 

回答

1

不僅速度更快,而且更直接地做一個服務器端的DataTables實現。從本質上講,你正在繪製一個完整的表格,然後完全重寫......這是非常低效的,並且在變得笨重之前可能無法處理超過幾百行的數據。

數據表,通過 「服務器端」 進行查詢:

$('#marketinghistory').dataTable({  
      "bDestroy":true, 
      "aaSorting": [[ 0, "desc" ]], 
      "bProcessing": true, 
      "bServerSide": true, 
      "sAjaxSource": "url of ajax source", 
      "bJQueryUI": true, 
      "sPaginationType": "full_numbers", 
      "bAutoWidth": false, 
      "bFilter":false, 
      "bLengthChange": true, 
      "bPaginate": true, 
      "bSort": true, 
      "iDisplayLength": 15, 
      "bInfo": true, 
      "aoColumns": [ 
        { "sTitle": "column title", "sWidth": "5%", "sClass":"center" }, 
        { "sTitle": "column title", "sWidth": "25%" , "sClass":"center"}, 
        { "sTitle": "column title", "sWidth": "10%", "sClass":"center" }, 
        { "sTitle": "column title", "sWidth": "5%", "sClass":"center" } 
      ] 
     }); 

現在,過濾,你有幾種選擇。如果您事先知道要做什麼,可以將它們作爲變量傳遞給「數據」字段,然後在服務器上進行排序。但是,你可能希望它是可變的......在這種情況下,還有更多的箍筋。上述

添加此代碼塊到數據表的代碼會允許你做變量過濾器:

"fnServerData": function (sSource, aoData, fnCallback) { 
       var name = $('#namesearch').val(); 
       var phone = $('#phonesearch').val(); 
       var company = $('#companysearch').val(); 

       aoData.push({ "name": "name", "value": name }, 
          { "name": "phone", "value": phone }, 
          { "name": "company", "value": company } 
       ); 

       $.ajax({ 
         "dataType": 'json', 
         "type": "POST", 
         "url": sSource, 
         "data": aoData, 
         "success": fnCallback 
       }); 
      } 

因此,變量設置爲輸入字段的值可用於過濾器的基礎上的網頁上用戶輸入。 aodata.push設置數據以推回回調,並且ajax回調完成這項工作。我在高級搜索頁面上使用這種模式,搜索字段在左側,數據表在右側。最初,空白字段沒有搜索過濾器,但隨着值被填充並且表格被重新繪製,服務器可以過濾查詢。

當然,這需要相當直接的後端設置來方便查詢。 A tut on that is here