如何从Ajax Call更新JQuery DataTables

时间:2017-08-09 10:10:46

标签: javascript jquery json asp.net-mvc datatables

我不想在加载时填充数据表。我希望从ajax调用返回json数据并将其绑定到datatable。这怎么可能?

$(function () {
var ajaxFormSubmit = function () {
    var $form = $(this);

    var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
    };

    $.ajax(options).done(function (data) {
        var $target = $($form.attr("data-search-target")); //resultsTable
        var $newHtml = $(data);

        $target.data = data; //QUESTION: How to update the datatable source here?

        var $target = $($form.attr("data-photo-target")); 


        //ANSWER
        $target.dataTable().fnClearTable();
        $target.dataTable().fnAddData(data);
    });

    return false;
};

$("form[data-search-ajax='true']").submit(ajaxFormSubmit);

$('#resultsTable').DataTable({
    "ajax": {
        "data": ""
    },
    "columns": [
        { "data": "Name", "autoWidth": true },
        { "data": "Date", "autoWidth": true },
        { "data": "File", "autoWidth": true },
        { "data": "Path", "autoWidth": true }
    ]
});
});

我的控制器按预期运行并返回json数据

[HttpGet]
public ActionResult Search(SearchData searchData)
{
    var searchViewModel = new SearchViewModel 
{
    SearchResults = _contentProvider.GetData(searchCriteria)
};

....

if (Request.IsAjaxRequest())
{
    return Json(searchViewModel.SearchResults, 
        JsonRequestBehavior.AllowGet);
    }
}
....

更新:我已编辑了以下评论中建议的原创和使用方法。请参阅下面添加的2行// ANSWER

0 个答案:

没有答案