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

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

问题描述

我知道我可以使用 ajax.url 对数据表发出 ajax 请求,例如 this :

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

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

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

<代码>...阿贾克斯":{网址":我的链接",数据":我的数据}...

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

在你的 DataTables ajax 部分,而不是使用 data<的 object 形式/code> 选项,您可以使用 function 形式.这允许您为每个新的 ajax 调用动态传递请求数据.

所以,而不是这样:

数据":我的数据

应该是这样的:

数据":函数(){返回我的数据;}

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

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


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

文档 展示了一个示例,使用 jQuery extend:

数据":函数 ( d ) {返回 $.extend( {}, d, {extra_search":$('#extra').val()});}

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

另一种处理方法是简单地将数据附加到data"中由d表示的数据结构:function (d):

数据":函数 ( d ) {d.extra_search = $('#extra').val();}


更新更详细的例子

这是一个完整的示例,如果您愿意,您可以将其复制到 html 文件中并自行运行.它使用来自虚拟 JSON 提供程序的数据,仅用于测试.

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

<button id="button_one";type="button">重新提交</button><br><br><table id="example"类=显示"样式=宽度:100%"></table>

以下是包含 DataTable 定义和调用新 URL(带有新请求参数)的函数的相关脚本:

这个例子的关键点是:

  1. 有 2 个不同的 URL.第一个在创建数据表时使用.点击按钮时使用第二个.

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

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


处理表单数据

这是一个简单的 HTML 表单:

城市:<输入类型=文本"id=城市"名称=城市">国家:<输入类型=文本"id=国家"名称=国家"><输入类型=提交"值=提交"></表单>

为了测试,我使用以下 JavaScript 将表单的内容捕获到数组中:

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

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

<预><代码>[{名称":城市",价值":柏林"},{名称":国家",价值":德国"}]

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

 $('#example').DataTable( {服务器端:真,阿贾克斯:{方法:POST",url: url,//来自一个变量数据:函数(d){返回 $.extend( {}, d, { "my_extra_data": form_data });}},...//无论您的 DataTable 定义中还有什么...});

这个函数产生如下的请求数据:

<代码>{平局":2",列[0][数据]":id",列[0][名称]":",...开始":0",长度":10",搜索[值]":",搜索[正则表达式]":假",my_extra_data[0][name]":城市",my_extra_data[0][value]":柏林",my_extra_data[1][name]":国家",my_extra_data[1][value]":德国"}

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

如果您使用的是 POST 那么它在请求正文中.

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

在这两种情况下,它都被转换为表单数据使用的标准字符串表示.

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

注意:您可能希望 URL 编码的表单数据提供如下:

...&city=柏林&国家=德国

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

&my_extra_data%5B0%5D%5Bvalue%5D=柏林&my_extra_data%5B1%5D%5Bname%5D=国家&my_extra_data%5B1%5D%5Bvalue%5D=德国

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

如果您想将表单数据直接转换成这样的 JavaScript 对象:

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

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

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

I know I can make ajax request on datatable using ajax.url like this :

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

...

table.ajax.url( 'newData.json' ).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
 }
 ...

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

解决方案

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.

So, instead of this:

"data" : myData

It would be this:

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

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

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


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.

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

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

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

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

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.

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>

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>

The key points in this example are:

  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.

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

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.


Handling Form Data

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> 

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

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

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

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"
}

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.

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

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.

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.

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:

Convert form data to JavaScript object with jQuery

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

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