单击按钮时更新数据表(JQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10160530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:53:41  来源:igfitidea点击:

Update datatables (JQuery) when button is clicked

jqueryjquery-datatables

提问by dimmat

I've created a simple form and I'm using the Datatables jQuery plugin to display some data in it. Data are being populated by a php script (process.php) which returns the proper results in JSON format. In the form, there is a button that sends the value of the textbox to the 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.

我创建了一个简单的表单,并使用 Datatables jQuery 插件在其中显示一些数据。数据由 php 脚本 (process.php) 填充,该脚本以 JSON 格式返回正确的结果。在表单中,有一个按钮将文本框的值发送到 process.php。问题是当单击按钮时,我无法使用 process.php 脚本收到的新数据更新/更改数据表

The code of the form:

表格代码:

<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> 

To create the datatable, I'm using the following JQuery code:

要创建数据表,我使用以下 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 script (works fine) is:

process.php 脚本(工作正常)是:

<?php
$result="";
if (empty($_REQUEST["txtId"])) {    
    $result = '{"aaData":[["1","Surname1","Name1"]]}';
}
else {
    $result = '{"aaData":[["2","Surname2","Name2"]]}';
}
print $result;
?>

采纳答案by Stefan

It looks like you should also specify fnServerDatawhen you setup your datable, if you want to use ajax POST: http://datatables.net/ref#fnServerData

fnServerData如果您想使用 ajax POST,您似乎还应该在设置数据时指定:http: //datatables.net/ref#fnServerData

It's also possible that you don't need to call fnReloadAjax(), but only fnDraw(). fnReloadAjax()is a plugin function, so I assume you did previously load it.

您也可能不需要调用fnReloadAjax(),而只需要调用fnDraw(). fnReloadAjax()是一个插件函数,所以我假设你之前加载过它。

回答by mbeasley

fnReloadAjaxis what you should use (and I believe that it might have a redraw built into the function). But the problem is that, although you make a second .ajax call, the data in that call is not associated with your datatable at all and will never be bound to it.

fnReloadAjax是你应该使用的(我相信它可能在函数中内置了重绘)。但问题是,尽管您进行了第二次 .ajax 调用,但该调用中的数据根本与您的数据表无关,并且永远不会绑定到它。

Using fnReloadAjaxwill make the same Ajax call that you specified in your table initialization. So what you need, as Stefan mentioned, is to specify your fnServerDataparameter in your datatable settings (but trash the Successparameters, because something along those lines is already assumed by datatables). Then just make your button call fnReloadAjax().

UsingfnReloadAjax将执行您在表初始化中指定的相同 Ajax 调用。因此,正如 Stefan 所提到的,您需要的是fnServerData在数据表设置中指定您的参数(但丢弃Success参数,因为数据表已经假定了这些方面的内容)。然后让你的按钮调用fnReloadAjax()

Here's what your final code should look like:

您的最终代码应该如下所示:

$(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();
    });
} );

回答by dimmat

At last, I found the solution! There were 2 problems in my JQuery code:

终于,我找到了解决方案!我的 JQuery 代码中有两个问题:

  1. I had to add the fnReloadAjax() code after the script tags which load datatables and before the $(document).ready() statement.
  2. I had to alter the JQuery code of my submit button (no need for an AJAX call, only fnReloadAjax() is necessary).
  1. 我必须在加载数据表的脚本标签之后和 $(document).ready() 语句之前添加 fnReloadAjax() 代码。
  2. 我不得不修改提交按钮的 JQuery 代码(不需要 AJAX 调用,只需要 fnReloadAjax())。

Thank you both Stefan & mbeasley!!

谢谢斯特凡和姆比斯利!!

JQuery code now is:

JQuery 代码现在是:

//
// 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());
        });

    } );

回答by James

You could alternatively just destroy the table and recreate it too.

您也可以只销毁表并重新创建它。

var oTable = null;

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

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

reloadTable();

回答by Rajapradeepan Rajendran

you can use.

您可以使用。

otable.ajax.reload()