如何修改查询数据表的ajax url?

Inf*_*ner 2 c# jquery asp.net-mvc-3

我想要做的是修改数据表的sAjaxSource,如果组合框中的值发生更改,然后我想调用数据表的fnDraw()函数

数据表是:

 $("#example").dataTable({
             "aoColumns": [
                     { "sTitle": "Id" },
                      { "sTitle": "Name" }],


             "bProcessing": true,
             "bServerSide": true,

             "sAjaxSource": '@Url.Action("FetchData", "Home")',
             "sPaginationType": "full_numbers",

});
Run Code Online (Sandbox Code Playgroud)

到目前为止我所拥有的是:C#代码:

public JsonResult GetData(DataTableParameters param, int? SelectedId)
 {
//return the results
}
Run Code Online (Sandbox Code Playgroud)

并且用于更改值的JavaScript代码是:

    $('#SelectedId').change(function () {
                alert("Hi");
                $("#example").dataTable(
                    {sAjaxSource:"/home/FetchData?SelectedId=1"}).fnDraw(true); ;
            });
Run Code Online (Sandbox Code Playgroud)

它达到警报("Hi")点,但它不会重绘表格.我如何让它工作?

Sha*_*ter 6

说明

要将API用于数据表,您需要先拥有句柄.该.dataTable函数返回创建的数据表的句柄.
所以,这样做

var oTable = $("#example").dataTable({
    ...
});

oTable.fnDraw();
Run Code Online (Sandbox Code Playgroud)

应该允许您访问和执行特定表的功能.


信息

数据表不支持在初始化后更改设置,这是有充分理由的.

//This does *NOT* work.
var oTable = $("#example").dataTable({
    ...
});
var oSettings = oTable.fnSettings();
oSettings.sAjaxSource = "some_url";
//Nothing will happen
oTable.Draw();
Run Code Online (Sandbox Code Playgroud)

但是,您可以尝试fnServerData在发送请求之前使用该函数拦截请求,然后只要发生更改,只需使用您自己的URL更新表.
或者
你可以破坏表并重新初始化它.

要了解有关fnServerData的更多信息,请单击此处并搜索"fnServerData".


我不确定这是否真的有效,我以前没有做过,但它应该有效.

var currentSource = "this_url";
var oTable = $('#example').dataTable( {
    "bServerSide": true,
    "bProcessing": true,
    "aoColumns": [
        {"sTitle": "id"},
        {"sTitle": "name"}
    ],
    "sPaginationType": "full_numbers",
    "sAjaxSource": currentSource,
    "fnServerData": function ( sSource, aoData, fnCallback ) {
        $.ajax( {
            "dataType": 'json',
            "type": "POST",
            "url": currentSource,
            "data": aoData,
            "success": fnCallback
        });
    }
});

$("#SelectedId").change(function)(){
    currentSource = "new_url";
    oTable.fnDraw(); //or fnReloadAjax()
});
Run Code Online (Sandbox Code Playgroud)

替代方案

另一种方法是销毁表,然后使用新设置重新初始化它.然而,这是处理它的一种非常无效的方式.

var initParams = {
    "bServerSide": true,
    "bProcessing": true,
    "aoColumns": [
        {"sTitle": "id"},
        {"sTitle": "name"}
    ],
    "sPaginationType": "full_numbers",
    "sAjaxSource": "this_url",
};
var oTable = $('#example').dataTable(initParams);

$("#SelectedId").change(function)(){
    oTable.fnDestroy();
    initParams.sAjaxSource = "new_url";
    oTable = $('#example').dataTable(initParams);
});
Run Code Online (Sandbox Code Playgroud)

边注

当你有bServerSide = true 必须照顾一切,这意味着它太复杂了一切!

快乐的编码!:)