如何通过使用新的URL和一些参数来重新加载数据表,而无需重新初始化它 [英] How to reload datatable by using new url and some parameters without reinitialize it

查看:67
本文介绍了如何通过使用新的URL和一些参数来重新加载数据表,而无需重新初始化它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用像 this :

var table = $('#example').DataTable( {
    ajax: "/mylink"
} );

...

table.ajax.url( 'newData.json' ).load();

但是如何使用相同的语法将数据作为参数传递给url?我尝试 table.ajax.url('mylink').data(myData).load(); .显然这不是解决方案.

But how can I pass data as parameters to url using the same syntax? I try table.ajax.url( 'mylink' ).data(myData).load(); . Obsviouly it is not solution.

我不想为了使用而销毁并重新初始化数据表:

I do not want to destroy and reinitialize the datatable in order to use :

...
"ajax" : {
        "url" : "mylink",
        "data" : myData
 }
 ...

我该怎么办?使用现有的初始化表(此处为js var表)的语法是什么?谢谢

What do I do? What is the syntax using existing initialized table (here js var table)? thanks

推荐答案

在您的数据表 ajax 部分中,而不是使用 data 选项,则可以使用 function 表单.这样,您就可以为每个新的ajax调用动态传递请求数据.

In your DataTables ajax section, instead of using the object form of the data option, you can use the function form. This allows you to dynamically pass in your request data for each new ajax call.

所以,代替这个:

"data" : myData

就是这样:

"data": function () {
  return myData;
}

而且,您已经注意到,可以使用 ajax.url()调用来指定新的URL:

And, as you already note, you can use the ajax.url() call to specify the new URL:

table.ajax.url( 'newData.json' ).load();


警告:这假定您不是在使用服务器端处理,因为这将覆盖由DataTables自动生成的服务器端请求数据.如果使用服务器端处理,则必须将自定义数据合并到预先存在的请求数据中.


Warning: This assumes you are not using server-side processing, as this will overwrite the server-side request data which is auto-generated by DataTables. If you are using server-side processing, then you have to merge your custom data into the pre-existing request data.

文档显示了使用jQuery extend :

The documentation shows an example for that, using jQuery extend:

"data": function ( d ) {
  return $.extend( {}, d, {
    "extra_search": $('#extra').val()
  } );
}

不需要使用 $.extend .您只需要注意不要覆盖由数据表生成的请求数据.

You don't need to use $.extend. You just need to be careful that you do not overwrite the request data generated by Datatables.

处理此问题的另一种方法是简单地将数据追加到"data":function(d):

Another way to handle this is to simply append data to the data structure represented by d in "data": function ( d ):

"data": function ( d ) {
  d.extra_search = $('#extra').val();
}


更新,其中包含更详细的示例


Update with a more detailed example

这里是完整的示例,您可以根据需要将其复制到html文件中并自行运行.它使用来自虚拟JSON提供程序的数据进行测试.

Here is a full example, which you can copy into a html file and run for yourself, if you wish. It uses data from a dummy JSON provider, just for testing.

HTML,显示表格和按钮.该按钮是我测试调用新URL并将新的请求参数传递到该新URL的能力的方式:

The HTML, showing the table and a button. The button is how I tested the ability to call a new URL and pass new request parameters to that new URL:

<div style="margin: 20px;">
    <button id="button_one" type="button">Resubmit</button>
    <br><br>
    <table id="example" class="display" style="width:100%"></table>
</div>

这里是相关的脚本,其中包含DataTable定义和一个函数,该函数调用新的URL(带有新的请求参数):

Here is the related script containing the DataTable definition and a function which calls the new URL (with new request parameters):

<script>

$(document).ready(function() {

  // ajax for initial table creation:
  var requestUrl = "https://jsonplaceholder.typicode.com/posts";
  var requestData = { "name": "Abel", "location": "here" };

  var table = $('#example').DataTable( {
    ajax: {
      method: "GET",
      url: requestUrl,
      "data": function ( ) {
        return requestData;
      },
      dataSrc: "",  
    },
    "columns": [
      { "title": "User ID", "data": "userId" },
      { "title": "ID", "data": "id" },
      { "title": "Title", "data": "title" }
    ]
            
  } );
  
  $("#button_one").click(function() {
    // subsequent ajax call, with button click:
    requestUrl = "https://jsonplaceholder.typicode.com/todos";
    requestData = { "name": "Charlie", "location": "there" };
    table.ajax.url( requestUrl ).load();
  });
  
} );

</script>

此示例中的关键点是:

  1. 有2个不同的URL.第一个在创建DataTables时使用.单击按钮时使用第二个.

  1. There are 2 different URLs. The first one is used when DataTables is created. The second one is used when the button is clicked.

对于两个URL,有两组不同的请求数据.

There are 2 different sets of request data, for the two URLs.

使用这种方法,您可以使用不同的URL和不同的请求数据集重复调用 table.ajax.url(requestUrl).load(),而无需破坏DataTable.

Using this approach, you can repeatedly call table.ajax.url( requestUrl ).load() with different URLs and different sets of request data, without needing to destroy the DataTable.

处理表单数据

这是一个简单的HTML表单:

Here is a simple HTML form:

<form id="filter-form">
    City:<input type="text" id="city" name="city">
    Country:<input type="text" id="country" name="country">
    <input type="submit" value="Submit">
</form> 

为了进行测试,我具有以下JavaScript,可将表单的内容捕获到数组中:

For testing, I have the following JavaScript which captures the contents of the form into an array:

var form_data = [];

$( "#filter-form" ).submit(function( event ) {
  event.preventDefault();
  form_data = $( this ).serializeArray();
  table.ajax.url( url ).load();
});

最终结果是在 form_data 变量中这样的数据:

The end result is data like this in the form_data variable:

[
  {
    "name": "city",
    "value": "Berlin"
  },
  {
    "name": "country",
    "value": "Germany"
  }
]

现在,我可以将该数据合并到自动创建的服务器端请求数据中.在这里,我可以选择使用上面提到的 $.extend()函数:

Now I can merge that data into the automatically created server-side request data. This is where I can choose to use the $.extend() function I mentioned above:

  $('#example').DataTable( {
    serverSide: true,
    ajax: { 
      method: "POST",
      url: url, // from a variable
      data: function( d ) {
        return $.extend( {}, d, { "my_extra_data": form_data } );
      }
    },
    ... //whatever else is in your DataTable definition...
  });

此函数产生如下请求数据:

This function results in request data like the following:

{
    "draw": "2",
    "columns[0][data]": "id",
    "columns[0][name]": "",
      ...
    "start": "0",
    "length": "10",
    "search[value]": "",
    "search[regex]": "false",
    "my_extra_data[0][name]": "city",
    "my_extra_data[0][value]": "Berlin",
    "my_extra_data[1][name]": "country",
    "my_extra_data[1][value]": "Germany"
}

您可以看到您的 my_extra_data 值与服务器端自动生成的请求数据一起包括在内.并将所有这些作为请求的一部分发送到服务器.

You can see your my_extra_data values are included along with the server-side auto-generated request data. And all of this gets sent to the server as part of your request.

如果您使用的是 POST ,则它位于请求正文中.

If you are using POST then it's in the request body.

如果您使用的是 GET ,则它们是相同的数据-但作为查询字符串添加到了URL.

If you are using GET, then it's the same data - but added to the URL as a query string.

在两种情况下,都将其转换为表单数据使用的标准字符串表示形式.

In both cases, it's converted to the standard string representation used by form data.

然后由服务器端代码以通常的方式访问此数据.

It's then up to the server-side code to access this data in the usual way.

注意:您可能希望以此方式提供URL编码的表单数据:

NOTE: You may have expected your URL-encoded form data to be provided as this:

...&city=Berlin&country=Germany

但是,它以名称/值对的数组形式提供:

But instead it is provided as arrays of name/value pairs:

&my_extra_data%5B0%5D%5Bvalue%5D=Berlin&my_extra_data%5B1%5D%5Bname%5D=country&my_extra_data%5B1%5D%5Bvalue%5D=Germany

因此,解析这些数据需要额外的服务器端工作.

So, there is extra server-side work needed to parse this data.

如果要直接将表单数据 转换为如下所示的JavaScript对象:

If you want to convert your form data directly into a JavaScript object like this:

{ "city": "Berlin", "country", "Germany" }

然后看看这个问题的答案:

then take a look at the answers to this question:

使用jQuery将表单数据转换为JavaScript对象

这篇关于如何通过使用新的URL和一些参数来重新加载数据表,而无需重新初始化它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆