weixin_33726318 2014-11-24 10:50 采纳率: 0%
浏览 22

如何在Ajax中使用数据表

I want to try pagination using datatables.net via ajax.

I have 2 input fields which sends start date and end date and following is the table structure

<table class="table table-hover" id="example">
              <thead>
          <tr>
          <th>Loan ID</th>
            <th>Date</th>
            <th>Loan Amount</th>
            <th>Loan Type</th>


          </tr>
        </thead>
        <tbody id="amount"></tbody></table>

when the button is clicked,I am calling this function

$('#recv').click(function(){
      var fromDate=$('#from').val();
      var toDate=$('#to').val();

      var test=$.ajax({
          type: "GET", 
           url: "/project/getDetails",  
              data:{"fromDate":fromDate,"toDate":toDate},
              dataType:"json",async:false 
      }).responseText;
      var result = eval('('+test+')');
      $('#example').dataTable( {
          "bServerSide": true,
            "sAjaxSource": result,
            "bProcessing": true,
            "aoColumns": [
                            { "sName": "Loan_ID",
                                "bSearchable": false,
                                "bSortable": false

                            },
                            { "sName": "Date" },
                            { "sName": "Loan_Amount" },
                            { "sName": "Loan_Type" }
                        ]
        } );

When Ever I click on the button then I get error in alert box saying datatables warning id=example ajax error

Can anybody please tell me how to solve?

  • 写回答

1条回答 默认 最新

  • weixin_33695450 2014-11-24 12:10
    关注

    Let datatables take care of the ajax call:

    var oTable = $('#example').dataTable( {
        "bServerSide": true,
        "iDeferLoading": 1,
        "sAjaxSource": "/project/getDetails",
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "fromDate", "value": $('#from').val() });
            aoData.push({ "name": "toDate", "value": $('#to').val() });
            },
        "bProcessing": true,
        "aoColumns": [
                      { "sName": "Loan_ID",
                        "bSearchable": false,
                        "bSortable": false
                      },
                    { "sName": "Date" },
                    { "sName": "Loan_Amount" },
                    { "sName": "Loan_Type" }
                  ]
            } );
    
    $('#recv').click(function(){
        oTable.fnDraw();
    });
    

    Points to note:

    • fnServerParams this passes your start & end date to the getDetails function
    • iDeferLoading - prevent table population on page load
    • fnDraw() populates the datatable from your click event
    评论

报告相同问题?