【问题标题】:Making an j query ajax call work both on page load and with a button click使 jquery ajax 调用在页面加载和单击按钮时都有效
【发布时间】:2016-07-13 02:20:22
【问题描述】:

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

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

我想要做的是,我希望在页面加载时加载带有空参数的数据表,然后单击按钮发送带有参数的 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 is not defined”错误。所以我觉得调用函数有问题。

【问题讨论】:

  • 只需在您的按钮单击事件中执行$('#expandabledatatable').Datatable().draw() 即可使表格执行 ajax 调用并再次构建表格
  • 就像一个侧节点:一个$(document).ready(function () {}); 可以解决问题。我不知道在同一个文件中多次使用它的任何原因。如果我错了,请纠正我。
  • 我对 jQuery 没有太多经验,我对此很陌生,所以你很可能是对的 caramba
  • @Reddy,没用 :(
  • @caramba 您可以拥有任意数量的$(document).ready(function () {});。没有必要把所有东西都塞进一个里面,甚至会适得其反,因为它会妨碍模块化。

标签: javascript jquery ajax datatables


【解决方案1】:

尝试以下方法:

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

请注意,这使用了Object.fromQueryString() from sugar.js,这是一个非常有用的库,提供了各种有用的东西。我将其包括在内是因为您的 getUrlParameter() 功能已损坏,不值得修复。已经编写了 URL 解析器,请使用现有的解析器。

如果您不想增加依赖项的数量,也可以将 moment.js 替换为 the Date functions provided by sugar.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 ...
    });
}

【讨论】:

  • 这看起来很不错,但在使用另一个库之前,我需要得到领导的确认 :(
  • 你不必使用sugar.js。我之所以包含它,是因为我碰巧非常喜欢它,因为它恰好提供了一个 URL 解析器,而且像这样的库往往会经过非常广泛的测试。关键是,您当前用于 URL 解析的功能已损坏,您不应该使用它。你可以选择一个比那个更好的函数,但我更喜欢来自经过良好测试的库的函数,而不是你从某个网站复制的函数。
猜你喜欢
  • 2011-04-07
  • 2013-09-09
  • 1970-01-01
  • 2014-02-08
  • 2011-04-10
  • 2014-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多