2012-05-15 274 views
0

我正在爲DataTables編寫服務器端處理代碼。我有一個UI頁面,我收集所有用戶輸入,如開始/結束日期,令牌ID,批次ID等。現在我必須將這些值傳遞給後端腳本,並在UI頁面中運行查詢並將輸出呈現給數據表。DataTables服務器端腳本的客戶端腳本

所以我有JS代碼來接受和驗證用戶輸入,但我不知道如何調用/設置數據表的params來狀態服務器端腳本。以下是我的腳本:

function runreport(datastring) 
{ 
     var oTable = $('#example').dataTable({ 
       "bProcessing": true, 
       "bServerSide": true, 
       "sAjaxSource": "runsearch.py", 
       "bDestroy" : true, 
       "fnServerData": function (sSource, aoData, fnCallback) { 
         $.ajax({ 
             "dataType": 'json', 
             "type": "POST", 
             "url": sSource, 
             "data": aoData, 
             "success": function(json) { 
               $("div#report_result").show(); 
               $('html, body').animate({scrollTop:$(document).height()}, 'slow'); 
               fnCallback(json); 
             } 
           }); 
       } 
     }); 
} 

當所有輸入參數都被驗證時,我調用'runreport'方法。我構造datastring就像查詢字符串:token_id = xxxx & [email protected] & start_date = 1212121212 & end_date = 98989898但這些值不被傳遞?我得到以下錯誤:

k is undefined 
[Break On This Error] 

...Sorting=="undefined"&&typeof e.saved_aaSorting=="undefined")e.aaSorting[a][1]=k.... 

jquery....min.js (line 150) 

我們應該怎麼做才能讓DataTables結果從後端腳本生成?

我沒有得到所需的結果輸出?這是調用服務器端processg的DataTables功能的正確方法嗎?

下面是我的Python代碼轉儲靜態結果集:

#!/usr/local/bin/python 

import cgi 
import MySQLdb 
import json 

print "Content-Type: application/json" 
print 

displaylength =5 
result = {'iDisplayLength':str(displaylength), 'sPaginationType':'full_numbers', 'bProcessing':1, 'bDestroy': 1, 'bRetrieve':1, 'aaData':[{'First Field':'First Field Value', 'Second Field':'Second Field Value', 'Third Field':'Third Field Value', 'Fourth Field':'Fourth Field Value', 'Fifth Field':'Fifth Field Value', 'Sixth Field':'Sixth Field Value', 'Seventh Field':'Seventh Field Value', 'Eight Field':'Eight Field Value', 'Nineth Field':'Nineth Field Value'}, {'First Field':'First Field Value', 'Second Field':'Second Field Value', 'Third Field':'Third Field Value', 'Fourth Field':'Fourth Field Value', 'Fifth Field':'Fifth Field Value', 'Sixth Field':'Sixth Field Value', 'Seventh Field':'Seventh Field Value', 'Eight Field':'Eight Field Value', 'Nineth Field':'Nineth Field Value'}], 'aoColumns':[{'sTitle':'First Field', 'mDataProp': 'First Field'},{ 'sTitle':'Second Field', 'mDataProp': 'Second Field'}, {'sTitle':'Third Field', 'mDataProp': 'Third Field' }, { 'sTitle':'Fourth Field', 'mDataProp': 'Fourth Field' }, { 'sTitle':'Fifth Field' , 'mDataProp': 'Fifth Field' }, { 'sTitle':'Sixth Field', 'mDataProp': 'Sixth Field' }, { 'sTitle':'Seventh Field', 'mDataProp': 'Seventh Field' }, { 'sTitle':'Eight Field', 'mDataProp': 'Eight Field' }, { 'sTitle':'Nineth Field', 'mDataProp': 'Nineth Field' }]} 

json_string = json.dumps(result) 
print json_string 

回答

0

有多種方法可以做到這一點。 DataTables支持AJAX source,因此您可以編寫一個腳本來輸出一個json數組並將其傳遞給DataTables插件。您也可以僅使用PHP呈現該表。

我想通過那裏的一些examples看看你可以傳遞數據到DataTables的其他方式。

+0

http://datatables.net/usage/#data_sources是的,我想使用服務器端處理,並想知道我的腳本有什麼問題? – Prakash

+0

你在用什麼語言編寫服務器端腳本?請分享該代碼。如果我看不到代碼,我不知道問題出在哪裏。 –

+0

我已經添加了用Python編寫的後端代碼 – Prakash

0

aoData.push是你要找的。將此用於您的fnServerData回調,替換您想要傳遞的值的aoData.push中的名稱和值。名稱將是關鍵和價值將是價值,$ _REQUEST變量傳遞:

​​

爲了測試它的工作,做出越來越Ajax請求簡單地寄給你的$ _REQUEST的頁面。你應該看到這些變量是其中的一部分。

回調的常見伴侶是添加一個按鈕來刷新表格。這只是通過將以下內容綁定到刷新按鈕上的點擊處理程序完成的:

oTable.fnDraw(false); 

祝你好運。

0

下面是一些數據表和服務器端/客戶端的我的C#代碼

你可以使用這個,如果你想將它轉換爲蟒蛇,我翻譯這個從阿蘭PHP例如

客戶方:

/* Instantiate the Datatables on the ASP.NET GridView */ 
var dt = $('#gvJobs').dataTable({ 
    "sDom": 'C<"clear">Rlfrtip', /* ColReOrder, ColVis */ 
    "bFilter": true, /* Use custom filters, i have to revise this as I am doing the drop down filter manually now */ 
    "bSort": true, 
    "bAutoWidth": false, 
    "bProcessing": true, /* Needed, Read Datatables documentation */ 
    "bServerSide": true, /* Needed, Read Datatables documentation */ 
    "aaSorting": [[0, "desc"]], /* Initial Default Sorting on the First Column */ 
    "sPaginationType": "full_numbers", 
    "fnServerData": function (sSource, aoData, fnCallback) { 
     /* Adding Custom Drop Down Filter property to aoData which will be used server side */ 
     aoData.push({ name: "ddlStatus", value: $("#ddlStatus option:selected").text() }); 

     /* Here I do the PageMethods call (ASP.NETs Ajax Replacement) PageMethods.getData 
     "getData" is a Server Side C# Method which looks like this: 

     [WebMethod] 
     public static string getData(List<oaData> aoData) 
     { 
     //Method Code 
     } 

     With page methods you pass in all your parameters matching the server side method, 
     And right at the end, add your two callback functions for onsuccess and onerror 
     */ 
     PageMethods.getData(aoData, function (obj) { 
      /* On Success, datatables fnCallback with JSON object */ 
      fnCallback(JSON.parse(obj)); 
     }, function (XMLHttpRequest, textStatus, errorThrown) { 
      /* On Error, show error alert */ 
      alert(XMLHttpRequest.status + ': ' + XMLHttpRequest.responseText); 
     }); 
    }, 
    "aoColumns": [ 
    /* This (JobNo) my first column which is Custom with 3 Images and a HyperLink to another page, 
    The last 5 Columns is hidden from the User because those fields are only used to 
    Render the correct images in this first column, Only used as Eval fields basically 

    Note that mDataProp is the GridView column's "DataField" and not the "HeaderText" 
    */ 
     { "mDataProp": "JobNo", 
      "fnRender": function (oObj) { 
      return "<img src='" + (oObj.aData.HasAttachments ? "css/paperclip-icon.png" : "css/empty-icon.png") + "' height='16px' />" 
        + "<a href='#' onclick=\"gotoJobDetail('" + oObj.aData.JobId + "');\">" + oObj.aData.JobNo + "</a>" 
        + "<img src='" + (oObj.aData.Visited ? "css/yes.png" : "css/no.png") + "' height='16px' />" 
        + "<img src='" + (oObj.aData.Completed ? "css/completed.png" : "css/notcompleted.png") + "' height='16px' />"; 
      }, 
      "bUseRendered": true /* This renders the Column in HTML first, else you'd see the actual HTML text in the column */ 
     }, 
     { "mDataProp": "JobStatusName" }, 
     { "mDataProp": "StatusDateTime" }, 
     /* Only used as Eval Field for one of the images in the JobNo Column */ 
     { "mDataProp": "HasAttachments", 
      "bSearchable": false, 
      "bVisible": false 
     }, 
     /* Only used as Eval Field for one of the images in the JobNo Column */ 
     {"mDataProp": "Visited", 
     "bSearchable": false, 
     "bVisible": false 
     }, 
     /* Only used as Eval Field for one of the images in the JobNo Column */ 
     {"mDataProp": "Completed", 
     "bSearchable": false, 
     "bVisible": false 
     }, 
     /* Just Hidden, not used at the moment neither by the user nor the application */ 
     {"mDataProp": "JobStatusId", 
     "bSearchable": false, 
     "bVisible": false 
     }, 
     /* Only used as Eval Field for one of the images in the JobNo Column */ 
     {"mDataProp": "JobId", 
     "bSearchable": false, 
     "bVisible": false 
     } 
    ] 
}); 

服務器端對象

//INCOMING OBJECT FROM CLIENTSIDE 
public class oaData 
{ 
    public string name { get; set; } 
    public string value { get; set; } 
} 

//RETURNING OBJECT TO CLIENTSIDE 
public class oaData<T> 
{ 
    public int sEcho { get; set; } 
    public int iTotalRecords { get; set; } 
    public int iTotalDisplayRecords { get; set; } 
    public T aaData { get; set; } 
    public string sColumns { get; set; } 
} 
//THIS IS 'T' IN oaData<T> 
public class JobOverviewDynamic 
{ 
    public int JobNo { get; set; } 
    public string JobStatusName { get; set; } 
    public string StatusDateTime { get; set; } 
    public bool HasAttachments { get; set; } 
    public bool Visited { get; set; } 
    public bool Completed { get; set; } 
    public int JobStatusId { get; set; } 
    public int JobId { get; set; } 
} 

Populat E中的對象,然後用JSON庫Newtonsoft它字符串化和返回 這裏是我的Serverside集團法

[WebMethod] 
public static string getData(List<oaData> aoData) 
{ 
    /* The Columns array 
    * If the array from Parameters is not empty, then use that 
    */ 
    string[] aColumns = { "JobNo", "JobStatusName", "StatusDateTime", "HasAttachments", "Visited", "Completed", "JobStatusId", "JobId" }; 
    var newCols = aoData.Where(n => n.name == "sColumns").Select(n => n.value).FirstOrDefault().Split(','); 
    aColumns = (newCols.Length == 1 && newCols[0] == "") ? aColumns : newCols; 

    /* Paging */ 
    var iDisplayStart = aoData.Where(n => n.name == "iDisplayStart").Select(n => n.value).FirstOrDefault(); 
    var iDisplayLength = aoData.Where(n => n.name == "iDisplayLength").Select(n => n.value).FirstOrDefault(); 

    /* Ordering */ 
    var sOrder = ""; 
    var iSortCol_0 = aoData.Where(n => n.name == "iSortCol_0").Select(n => n.value).FirstOrDefault(); 
    if (iSortCol_0 != null && aColumns.Length > 0) 
    { 
     sOrder = "ORDER BY "; 
     var iSortingCols = aoData.Where(n => n.name == "iSortingCols").Select(n => int.Parse(n.value)).FirstOrDefault(); 
     for (int i = 0; i < iSortingCols; i++) 
     { 
      var iSortCol = aoData.Where(n => n.name == "iSortCol_" + i).Select(n => int.Parse(n.value)).FirstOrDefault(); 
      var bSortable = aoData.Where(n => n.name == "bSortable_" + iSortCol).Select(n => bool.Parse(n.value)).FirstOrDefault(); 

      if (bSortable) 
      { 
       var sSortDir = aoData.Where(n => n.name == "sSortDir_" + i).Select(n => n.value).FirstOrDefault(); 
       sOrder += aColumns[iSortCol] + " " + sSortDir + ", "; 
      } 
     } 
     sOrder = sOrder.Trim(); 
     sOrder = sOrder.Substring(sOrder.Length - 1) == "," ? sOrder.Substring(0, sOrder.Length - 1) : sOrder; 
     sOrder = (sOrder == "ORDER BY") ? "" : sOrder; 
    } 

    /* Filtering 
    */ 
    var sWhere = ""; 
    var sSearch = aoData.Where(n => n.name == "sSearch").Select(n => n.value).FirstOrDefault(); 
    var status = aoData.Where(n => n.name == "ddlStatus").Select(n => n.value).FirstOrDefault(); 
    if (sSearch != "" && aColumns.Length > 0) 
    { 
     sWhere = "WHERE ("; 
     for (int i = 0; i < aColumns.Count(); i++) 
     { 
      sWhere += aColumns[i] + " LIKE '%" + sSearch + "%'" + (i < aColumns.Count() - 1 ? " OR " : " "); 
     } 
     sWhere = sWhere.Trim() + ")"; 
    } 

    /* Individual column filtering */ 
    for (int i = 0; i < aColumns.Count(); i++) 
    { 
     var bSearchableCol = aoData.Where(n => n.name == "bSearchable_" + i).Select(n => bool.Parse(n.value)).FirstOrDefault(); 
     var sSearchCol = aoData.Where(n => n.name == "sSearch_" + i).Select(n => n.value).FirstOrDefault(); 

     if (bSearchableCol && sSearchCol != "") 
     { 
      sWhere = (sWhere == "") ? "WHERE " : sWhere + " AND "; 
      sWhere += aColumns[i] + " LIKE '%" + sSearchCol + "%' "; 
     } 

     /* Added this second if statement for my custom drop down filter on a specific column 
     * The fnFilter setting with a column number does not work, and this way, ColReorder will still work 
     */ 
     if (status != "" && aColumns[i] == "JobStatusName") 
     { 
      sWhere = (sWhere == "") ? "WHERE " : sWhere + " AND "; 
      sWhere += aColumns[i] + " = '" + status + "' "; 
     } 
    } 

    /* SQL queries 
    * Get data to display 
    */ 
    List<LTS.JobOverviewDynamicResult> data; 
    using (var m = new Methods()) 
    { 
     //Im not giving my SQL query 
     data = m.getJobOverviewDynamicData(sWhere, sOrder, iDisplayStart, iDisplayLength); 
    } 

    int iFilteredTotal = 0; 
    int iTotal = 0; 
    if (data.Count() > 0) 
    { 
     /* Filtered dataset and Total dataset length */ 
     iFilteredTotal = (int)data.FirstOrDefault().ITotalFiltered; 
     iTotal = (int)data.FirstOrDefault().ITotal; 
    } 

    /* Output */ 
    var sEcho = aoData.Where(n => n.name == "sEcho").Select(n => int.Parse(n.value)).FirstOrDefault(); 
    var output = new oaData<List<JobOverviewDynamic>>() 
    { 
     sEcho = sEcho, 
     iTotalRecords = iTotal, 
     iTotalDisplayRecords = iFilteredTotal, 
     aaData = data.Select(n => new JobOverviewDynamic() 
     { 
      JobNo = (int)n.JobNo, 
      JobStatusName = n.JobStatusName, 
      StatusDateTime = ((DateTime)n.StatusDateTime).ToString("yyyy-MM-dd hh:mm"), 
      HasAttachments = (bool)n.HasAttachments, 
      Visited = (bool)n.Visited, 
      Completed = (bool)n.Completed, 
      JobStatusId = (int)n.JobStatusId, 
      JobId = (int)n.JobId 
     }).ToList(), 
     sColumns = string.Join(",", aColumns) 
    }; 

    return JsonConvert.SerializeObject(output); 
} 

我希望這是有點意義上說,如果不是 - 問我應協助。

相關問題