Datatables and jQuery $.post

2019-08-29 08:12发布

问题:

I have a datatables table in my webpage with more than one page of paginated data in it. Per the example given by datatables, I use the following javascript/jQuery to submit the form:

<script>
var oTable;
$(document).ready(function() {
    $('#form').submit( function() {
        var sData = oTable.$('input').serialize();
        $.post('', sData); // WORKS
        // $.post('', sData, $('body').html(data)); // DOES NOT WORK
        return false;
    } );

    oTable = $('#meters').dataTable();
} );
</script>

When I post via $.post('', sData);, all of my table rows are posted. When I post with $.post('', sData, $('body').html(data));, only the rows of the visible page of the table are posted. Why?

I'm fairly new to jQuery -- perhaps I am missing something...

Here is the code I use to initialize the table:

<script>    

/* Create an array with the values of all the input boxes in a column */
$.fn.dataTableExt.afnSortData['dom-text'] = function  ( oSettings, iColumn )
{
    var aData = [];
    $( 'td:eq('+iColumn+') input:last', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( this.value );
    } );
    return aData;
}

/* Create an array with the values of all the select options in a column */
$.fn.dataTableExt.afnSortData['dom-select'] = function  ( oSettings, iColumn )
{
    var aData = [];
    $( 'td:eq('+iColumn+') select:last', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( $(this).val() );
    } );
    return aData;
}

/* Create an array with the values of all the checkboxes in a column */
$.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, iColumn )
{
    var aData = [];
    $( 'td:eq('+iColumn+') input:last', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( this.checked==true ? "1" : "0" );
    } );
    return aData;
}

    $(document).ready(function() {
        $('#meters').dataTable(
            {
                "aoColumns": [
                    { "sSortDataType": "dom-text" },
                    { "sSortDataType": "dom-select" },
                    { "sSortDataType": "dom-checkbox" },
                ],
                "aoColumnDefs": [
                    { 
                        "aTargets":     ["vbNoSearchSort"],
                        "bSearchable":  false,
                        "bSortable":    false
                    }
                ],
                "bProcessing"   :true,
                "bStateSave"    :true,
                "sPaginationType": "full_numbers"
            }
        );
    } );
</script>

回答1:

because it needs to be a closure or a reference to a function.

$.post('', sData, function(data){$('body').html(data); }); 

or

function callback(data) {
   $('body').html(data);
}
$.post('', sData, callback);