使j查询ajax调用既适用于页面加载,也适用于单击按钮



我有一个数据表,它从ajax调用中获取数据。通常,ajax在加载页面并获取充满数据的数据表时运行。

但我也想在我的数据表中添加一些搜索选项。我可以将参数发送到服务器端,并使用fiters返回数据集。

我想做的是,我希望在页面加载时用null参数加载数据表,然后点击一个按钮,发送带有参数的ajax并返回过滤后的数据。

我试过的是这个

<script>
    //var searchInput ;//search için aramadaki değeri almaya çalışma
    $(document).ready(function TableData(searchInput) {
        var getUrlParameter = function getUrlParameter(sParam) {
            var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;
            for (i = 0; i < sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');
                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : sParameterName[1];
                }
            }
        };
        //var searchInput = $("#inpSearch").val();//search için aramadaki değeri almaya çalışma
        var DocumentTypeId = getUrlParameter('DocumentTypeId');
        var Type = getUrlParameter('Type');
        //console.log("dokumantip: " + DocumentTypeId);
        //console.log("tip: " + Type);
        var datatable = null;
        $(document).ready(function () {
            $.extend(true, $.fn.dataTable.defaults, {
                "searching": false,
                "ordering": false
            });

            @*var dataSourceUrl = "@Url.Action(  Inbox ? "InboxList" : "OutboxList" ,"Folder")";*@
            @*var dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")";*@
            if (Type == 1) {
                var dataSourceUrl = "@Url.Action( Inbox ? "ERPListByType" : "OutboxList" ,"Folder")";
            } else if (Type == 2) {
                var dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")";
            } else if (Type == 3) {
                var dataSourceUrl = "@Url.Action( Inbox ? "OutboxListByType" : "OutboxList" ,"Folder")";
            } else if (Type == 4) {
                var dataSourceUrl = "@Url.Action( Inbox ? "DeletedDocumentsList" : "OutboxList" ,"Folder")";
            } else {
                //açılış ekranında default gelen kutusu e-TCGB gelsin
                var dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder", new { DocumentTypeID = 3 })";
            }
            if ($.fn.dataTable.isDataTable('#expandabledatatable')) {
                $('#expandabledatatable').dataTable().fnDestroy();
            }
            datatable = $('#expandabledatatable').dataTable({
                //"sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
                //"processing": true,
                //info: false,
                serverSide: true,
                ajax: {
                    "url": dataSourceUrl,
                    "data": { DocumentTypeId: DocumentTypeId, searchInput: searchInput },
                    "type": "POST"
                },
                columns: [
                    {
                        "data": "Id",
                        "render": function (data, type, row) {
                            return "<label><input type='checkbox' value='" + data + "' name='chkGrid'><span class='text'></span></label>";
                        }
                    },
                    { "data": "@Html.Raw(Inbox ? "SenderCompany" : "ReceiverCompany")" },
                    { "data": "DocumentTypeName" },
                    {
                        "data": "RegistrationDate",
                        "render": function (data, type, row) {
                            return moment(parseInt(data.substr(6))).format('DD.MM.YYYY hh:mm');
                        }
                    },
                    {
                        "data": "RegistrationCode",
                        "render": function (data, type, row) {
                            console.log(row);
                            return "<a href='@Url.Action("View","Folder")/" + row["Id"] + "'>" + data + "</a>";
                        }
                    },
                    { "data": "CustomsTransportType" },
                    { "data": "VehicleIdNo" },
                    { "data": null, "defaultContent": "" },
                    { "data": "ConsignorName" },
                    { "data": "ConsigneeName" },
                    { "data": "TotalNoOfPackages" },
                    { "data": "TotalGrossWeight" }
                ],
                iDisplayLength: 10,
                language: {
                    "info": "Toplam kayıt : _TOTAL_<br/> Gösterilen : _START_ - _END_",
                    "paginate": {
                        "first": "İlk",
                        "last": "Son",
                        "next": "İleri",
                        "previous": "Geri"
                    }
                }
            });

        });
    });

    $(document).ready(function () {
        $('#btnSearch').click(function () {
            alert("test");
            TableData($('#inpSearch').val())
        })
    });

</script>

我试图用一个参数在jquery函数中获取ajax事件,这样我就可以在搜索按钮中点击。但我不能让它按我想要的方式工作。

编辑:

数据作为从ActionResult返回

string DatatableJson = Utility.DatatableToJson(ds.Tables[0]);
return Content("{ "draw": " + Draw + ", "recordsTotal" :" + TotalRows + " , "recordsFiltered": " + TotalRows + ", "data": " + DatatableJson + " } ");

ds是通过存储过程从数据库返回的数据表。

编辑2:

我注意到

$('#btnSearch').click(function () {
            //alert($('#inpSearch').val());
            var search = $('#inpSearch').val();
            TableData(search);
            $('#expandabledatatable').Datatable().draw();
        })

给出"ReferenceError:TableData未定义"错误。所以我想我在调用函数时遇到了问题。

尝试以下操作:

$(document).ready(function () {
    var url = Object.fromQueryString(window.location.search);
    $.extend(true, $.fn.dataTable.defaults, {
        searching: false,
        ordering: false
    });
    $('#btnSearch').click(function () {
        doSearch( $('#inpSearch').val(), url.Type, url.DocumentTypeId);
    });
    // click the button (do a search) on page load once
    $('#btnSearch').click();
});

请注意,它使用了sugar.js中的Object.fromQueryString(),这是一个非常有用的库,提供了各种有用的东西。我把它包括在内是因为你的getUrlParameter()函数坏了,不值得修复。URL解析程序已经编写完毕,请使用现有的解析程序。

如果您不想增加依赖项的数量,您可能也可以用sugar.js提供的Date函数替换moment.js。

我创建了一个doSearch()函数,它不依赖于任何数据,除了参数中传递的数据。这样,函数可以更容易地重复使用。

function doSearch(searchInput, documentTypeId, type) {
    var dataSourceUrl;
    switch (type) {
        case 1: dataSourceUrl = "@Url.Action( Inbox ? "ERPListByType" : "OutboxList" ,"Folder")"; break;
        case 2: dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")"; break;
        case 3: dataSourceUrl = "@Url.Action( Inbox ? "OutboxListByType" : "OutboxList" ,"Folder")"; break;
        case 4: dataSourceUrl = "@Url.Action( Inbox ? "DeletedDocumentsList" : "OutboxList" ,"Folder")"; break;
        default: dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")"; break;
    }
    if ($.fn.dataTable.isDataTable('#expandabledatatable')) {
        $('#expandabledatatable').dataTable().fnDestroy();
    }
    $('#expandabledatatable').dataTable({
        //sDom: "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
        //processing: true,
        //info: false,
        serverSide: true,
        ajax: {
            url: dataSourceUrl,
            data: { DocumentTypeId: documentTypeId, searchInput: searchInput },
            type: "POST"
        },
        // etc ...
    });
}

最新更新