jQuery 使用新参数重新加载 Ajax 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32560635/
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 16:54:07  来源:igfitidea点击:

Reload Ajax request with new parameters

jquerydatatables

提问by Muflix

I obtain table data from database via AJAX request. And I need to change data parameter in AJAX request and refresh the table.

我通过 AJAX 请求从数据库中获取表数据。我需要更改 AJAX 请求中的数据参数并刷新表。

I am refreshing table with command

我正在用命令刷新表格

$('#table1').DataTable().ajax.reload();

I have the following code

我有以下代码

$('#table1').DataTable({

    /* SERVER SIDE PROCESSING */
                "serverSide": true,
                "ajax":
                    {
                        "url": "Home/Search",
                        "type": "POST",

                        "data": {
                            'searchType': GetSearchType(),
                            'searchText': GetSearchText()
                            //'searchType': $.mynamespace.searchType
                            //'searchText': $.mynamespace.searchText
                            //'searchType': localStorage.getItem("searchType"),
                            //'searchText': localStorage.getItem("searchText"),
                        }
                    }
            });

But after AJAX reload, original request to the server is sent and new parameter values are ignored. I tried pass the data to the request via function, global variable and browser storage but none of the approach work. On the internet I find solution with

但是在 AJAX 重新加载后,向服务器发送原始请求并忽略新的参数值。我尝试通过函数、全局变量和浏览器存储将数据传递给请求,但没有一种方法有效。在互联网上,我找到了解决方案

aoData.push() 

function but I don't know how to use it.

功能,但我不知道如何使用它。

My version of jQuery DataTables is 1.10.7.

我的 jQuery DataTables 版本是 1.10.7。

I also tried destroying and recreating the table with this code:

我还尝试使用以下代码销毁并重新创建表:

$('#table1').DataTable({
        "ajax":
            {
                "url": "Home/Search",
                "type": "POST",

                "data": {
                    'searchType': GetSearchType(),
                    'searchText': GetSearchText()
                }
            },
        "destroy" : true
    }).ajax.reload();

but I am getting error message:

但我收到错误消息:

DataTables warning: table id=table1 - Ajax error (http://www.datatables.net/manual/tech-notes/7)

The parameters dictionary contains a null entry for parameter 'draw' of non-nullable type 'System.Int32'

数据表警告:表 id=table1 - Ajax 错误 ( http://www.datatables.net/manual/tech-notes/7)

参数字典包含不可为空类型“System.Int32”的参数“draw”的空条目

回答by Gyrocode.com

You can use function as a value for ajax.dataoption as shown below.

您可以使用函数作为ajax.data选项的值,如下所示。

That way your code will be run every time the client makes request to the server and not once as with your initial code.

这样,您的代码将在每次客户端向服务器发出请求时运行,而不是像您的初始代码那样运行一次。

$('#table1').DataTable({
   "serverSide": true,
   "ajax": {
      "url": "Home/Search",
      "type": "POST",
      "data": function(d){
         d.searchType = GetSearchType();
         d.searchText = GetSearchText();
      }
   }
});

Then use $('#table1').DataTable().ajax.reload()when you need to reload the table or $('#table1').DataTable().ajax.reload(null, false)if you don't want to reset the current page. See ajax.reload()for more information.

然后$('#table1').DataTable().ajax.reload()在需要重新加载表格或$('#table1').DataTable().ajax.reload(null, false)不想重置当前页面时使用。有关ajax.reload()更多信息,请参阅。

回答by Mehmet Emre Vural

$('#table1').DataTable().ajax.url("?some_param=1&another=2").load();

This is an another solution. Add your params inside default datatable params.

这是另一种解决方案。在默认数据表参数中添加您的参数。

How to set dynamically the Ajax URL of a dataTable?

如何动态设置dataTable的Ajax URL?

回答by Muflix

Okay I found the solution, in the reinitializing of the table, it is needed to specify all settings again otherwise they are taken from default. so the final code is

好的,我找到了解决方案,在重新初始化表时,需要再次指定所有设置,否则它们将采用默认设置。所以最终的代码是

$('#table1').DataTable({
            "iDisplayStart": 0,
            "iDisplayLength": 50,
            "bPaginate": true,
            "bSort": false,
            "serverSide": true,
             /* and all others settings others than default */
        "ajax":
            {
                "url": "Home/Search",
                "type": "POST",

                "data": {
                    'searchType': GetSearchType(),
                    'searchText': GetSearchText()
                }
            },
        "destroy" : true  /* <---- this setting reinitialize the table */
    }).

but if someone will find better solution, please share it.

但如果有人会找到更好的解决方案,请分享。

回答by Sanchitos

This is how i accomplish it:

这是我如何实现它:

var onSearchClick = function () { search(); };

var onSearchClick = function () { search(); };

    var search = function () {


        var startDate =  $('#datetimepicker1').find("input").val();
        var endDate = $('#datetimepicker2').find("input").val();

        $.ajax({
            type: "GET",
            url: "/api/getByDate?startDate=" + startDate + "&endDate="+endDate,
            datatype: "json",
            traditional: true
        })
        .done(function (data) {

          var table = $('#data-table-1').DataTable({
              data: data.data,
              destroy: true,
              "columns": [
             { "data": "id" },
             { "data": "id2" },
             { "data": "id3" }
              ],
              "columnDefs": [
           {
               "targets": [1],
               "visible": false,
               "searchable": false
           },
            {
                "targets": [2],
                "visible": false,
                "searchable": false
            }],
              "sPaginationType": "full_numbers"
          });
      });
    };

回答by sam ruben

AJAX loads header as a variable on first time when page loads. When you changed the headers and do some sorting/searching. New headers will not be set unless you set new headers using "beforeSend".I have provided the sample code.

AJAX 在页面加载时第一次将标头作为变量加载。当您更改标题并进行一些排序/搜索时。除非您使用“beforeSend”设置新标题,否则不会设置新标题。我提供了示例代码。

Try this,

尝试这个,

$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('ajax', {
    url: 'url',
    'beforeSend': function (request) {
        request.setRequestHeader("Authorization","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9");
        request.setRequestHeader("Subscription-Key","1d64412357444dc4abc5fe0c95ead172");
    } ,

    //},
    type: "POST",
    cache: false, // It will not use cache url

})