Вопрос по jquery – Обновление таблиц данных (JQuery) при нажатии кнопки

8

Я создал простую форму и использую плагин Datatables jQuery, чтобы отобразить в нем некоторые данные. Данные заполняются скриптом php (process.php), который возвращает правильные результаты в формате JSON. В форме есть кнопка, которая отправляет значение текстового поля в process.php.The problem is that I cannot update/alter datatable with the new data received by process.php script when the button is clicked.

Код формы:

<form name="myform" id="myform" action="" method="POST">  
    <label for="id">Enter an id:</label>  
    <input type="text" name="txtId" id="txtId" value=""/> 
    <input type="button" id="btnSubmit" name="btnSubmit" value="Search"> 
</form>

<div id="results">
    <table class="display" id="example">
        <thead>
            <tr>
                <th>id</th>
                <th>Surname</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <!-- data goes here -->
        </tbody>
    </table>
</div> 

Чтобы создать таблицу данных, я использую следующий код JQuery:

    $(document).ready(function() {
            var oTable = $('#example').dataTable( {
                "sPaginationType": "full_numbers",
                "iDisplayLength": 10,
                //"bServerSide": true,
                "sAjaxSource": "process.php"
            } );

        $("#btnSubmit").click(function(){
            $.ajax({  
                type: "POST",  
                url: "process.php",  
                data: 'txtId=' + $("txtId").val(),  
                success: function(result) {  
                    oTable.fnReloadAjax();
                    oTable.fnDraw();
                }  
            });
        });
    } );

Скрипт process.php (работает нормально):

<?php
$result="";
if (empty($_REQUEST["txtId"])) {    
    $result = '{"aaData":[["1","Surname1","Name1"]]}';
}
else {
    $result = '{"aaData":[["2","Surname2","Name2"]]}';
}
print $result;
?>
Error: User Rate Limit Exceeded dimmat
neverError: User Rate Limit Exceededjson_encode()Error: User Rate Limit Exceededecho json_encode(array('aaData' => array(array('1', 'Surname1', 'Name1')))); ThiefMaster♦

Ваш Ответ

5   ответов
0

otable.ajax.reload()

1

fnServerData

fnReloadAjax()fnDraw(). fnReloadAjax()

Error: User Rate Limit Exceeded dimmat
Error: User Rate Limit Exceeded dimmat
Error: User Rate Limit Exceeded dimmat
Error: User Rate Limit ExceededfnServerDataError: User Rate Limit Exceeded
4

fnReloadAjaxError: User Rate Limit Exceeded

Error: User Rate Limit ExceededfnReloadAjaxError: User Rate Limit ExceededfnServerDataError: User Rate Limit ExceededSuccessError: User Rate Limit ExceededfnReloadAjax().

Error: User Rate Limit Exceeded

$(document).ready(function() {
        var oTable = $('#example').dataTable( {
            "sPaginationType": "full_numbers",
            "iDisplayLength": 10,
            "sAjaxSource": "process.php",
            "fnServerData": function ( sSource, aoData, fnCallback ) {
                $.ajax( {
                    "dataType": 'json', 
                    "type": "POST", 
                    "url": sSource, 
                    "data": 'txtId=' + $("txtId").val(), 
                    "success": fnCallback
                } );
            }
        } );

    $("#btnSubmit").click(function(){ 
        oTable.fnReloadAjax();
    });
} );
Error: User Rate Limit ExceededfnServerDataError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededdatatables.net/plug-ins/apiError: User Rate Limit Exceeded dimmat
3


I had to add the fnReloadAjax() code after the script tags which load datatables and before the $(document).ready() statement. I had to alter the JQuery code of my submit button (no need for an AJAX call, only fnReloadAjax() is necessary).

//
// fnReloadAjax() code      
//
    $.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
    {
        if ( typeof sNewSource != 'undefined' && sNewSource != null )
        {
            oSettings.sAjaxSource = sNewSource;
        }
        this.oApi._fnProcessingDisplay( oSettings, true );
        var that = this;
        var iStart = oSettings._iDisplayStart;
        var aData = [];

        this.oApi._fnServerParams( oSettings, aData );

        oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
            /* Clear the old information from the table */
            that.oApi._fnClearTable( oSettings );

            /* Got the data - add it to the table */
            var aData =  (oSettings.sAjaxDataProp !== "") ?
                that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;

            for ( var i=0 ; i<aData.length ; i++ )
            {
                that.oApi._fnAddData( oSettings, aData[i] );
            }

            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
            that.fnDraw();

            if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
            {
                oSettings._iDisplayStart = iStart;
                that.fnDraw( false );
            }

            that.oApi._fnProcessingDisplay( oSettings, false );

            /* Callback user function - for event handlers etc */
            if ( typeof fnCallback == 'function' && fnCallback != null )
            {
                fnCallback( oSettings );
            }
        }, oSettings );
    }


    $(document).ready(function() {

        var oTable = $('#example').dataTable( {
            "sPaginationType": "full_numbers",
            "iDisplayLength": 10,
            //"bServerSide": true,
            "sAjaxSource": "process.php"
        });

        $("#btnSubmit").click(function(){
            oTable.fnReloadAjax("process.php?txtId=" + $("txtId").val());
        });

    } );
0

var oTable = null;

function reloadTable() {
    if (oTable) {
        oTable.fnDestroy();
    }

    oTable = $('#example').dataTable( {
        "sPaginationType": "full_numbers",
        "iDisplayLength": 10,
        //"bServerSide": true,
        "sAjaxSource": "process.php"
    } );
}

reloadTable();

Похожие вопросы