如何在DataTables中动态设置Ajax数据? [英] How do you dynamically set ajax data in DataTables?
问题描述
我正在使用DataTables 1.10.15,并已了解如何在ajax调用中指定data
属性,如下所示:
I'm using DataTables 1.10.15 and have read about how you can specify the data
attribute in an ajax call like so:
$(document).ready(function() {
var MyTable = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/server_processing.php",
"data": function ( d ) {
d.myKey = "myValue";
// d.custom = $('#myInput').val();
// etc
}
}
} );
} );
但是,此示例仅具有硬编码的值(或诸如$('#myInput').val()
的形式的输入值).
However, this example just has hardcoded values (or form input values like $('#myInput').val()
).
我有一个应用程序,需要传递各种不同的数据对象,然后运行ajax调用.
I have an application where I need to be able to pass in various different objects of data and then have the ajax call run.
我看不到这是怎么可能的,并查看了以下 https://datatables.net/examples/server_side/custom_vars.html .
I can't see how this is possible and have looked at the following https://datatables.net/examples/server_side/custom_vars.html.
我要这样做的原因是因为我正在构建具有几种不同形式的应用程序.我需要选择哪种形式作为数据发送!当用户以特定形式输入字词时,我想将那个表单数据传递给我的ajax脚本,然后让DataTables重绘该表(我可以使用.draw()
方法来做到):>
The reason I want to do this is because I'm building an application with several different forms. I need to choose which form to send as the data! When the users enter terms in a particular form, I want to pass that forms data to my ajax script and then have DataTables redraw the table (which I can do using the .draw()
method):
MyTable.draw();
但是,我不明白如何动态指定data:
中的内容.我可以在ajax调用中做类似的事情:
However, I don't understand how I can dynamically specify what goes in data:
. I could do something like this in the ajax call:
"ajax": {
"url" : "scripts/server_processing.php",
"data" : function ( d ) {
d.primarySearch = $('#form1').serialize(),
d.secondSearch = $('#form2').serialize(),
d.thirdSearch = $('#form3').serialize(),
}
}
但是,如果我正在搜索的数据在#form1
中,我只想传递该数据,而不是#form2
和#form3
中的数据.但是由于每次都不同,因此我必须能够说出要传递给data:
对象的形式.
But, if the data I'm doing the search on is in #form1
, I just want to pass that data, and not the data from #form2
and #form3
. But since that varies each time, I need to be able say which form(s) to pass in to the data:
object.
推荐答案
我也在使用服务器端处理. 您可以按照以下代码进行调用:
I am also using the server side processing. you can call it as per below code:
这是用于静态表单ID
This is for static form id
ajax: {
"url": 'api/v1/datatable/' + method,
"type": "POST",
"data": jQuery('#frmid').serialize(),
},
这是用于动态表单ID
This is for dynamic form id
var form_id = 'form1' ;
$(document).ready(function() {
var MyTable = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/server_processing.php",
"data": jQuery('#' + form_id).serialize(),
}
} );
} );
$(document).on('keyup','.search_text',function(){
form_id = $(this).closest('form').attr('id');
MyTable.draw();
})
希望这对您有所帮助.
这篇关于如何在DataTables中动态设置Ajax数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!