Vij*_* V. 4 javascript jquery datatables
我试图发布表单数据但没有成功,无法加载数据.
如何将包含数组和单个文本框,组合框等的所有表单数据传递给fnServerdata?
table_obj = $('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
aaSorting: [[ 1, "desc" ]],
bProcessing: true,
bServerSide: true,
processing : true,
columnDefs: [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<label><input type="checkbox" name="user_id[]" value="' + $('<div/>').text(data).html() + '"></label>';
}
}],
rowCallback: function(row, data, dataIndex){
// If row ID is in list of selected row IDs
if($.inArray(data[0], rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
},
iDisplayLength: '50',
});
Run Code Online (Sandbox Code Playgroud)
小智 14
如果要格式化POST数据,还可以使用jquery .each()函数格式化表单数据.让我使用上面的解决方案使用解决方案#1但是使用jquery .each()格式化数据.
$('table').DataTable({
"ajax": {
"url": "URL HERE",
"type": "POST",
"data": function(d) {
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
然后你可以在PHP中访问它,如:
var $data = $_POST['name'];
Run Code Online (Sandbox Code Playgroud)
解决方案1
替换这个:
$('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
Run Code Online (Sandbox Code Playgroud)
和:
$('#group-table').dataTable({
"ajax": {
"url": "URL Goes here",
"type": "POST",
"data": function(d){
d.form = $("#frm").serializeArray();
}
},
Run Code Online (Sandbox Code Playgroud)
您的表单数据将作为带有参数和form的对象数组存在于参数中,下面是 JSON 表示形式:namevalue
"form": [{"name":"param1","value":"val1"},{"name":"param2","value":"val2"}]
Run Code Online (Sandbox Code Playgroud)
解决方案2
如果您希望将表单数据作为名称/值对,请参阅此 jsFiddle以获取替代解决方案的示例。
笔记
您的数据表中有复选框。上面的解决方案不适用于数据表中的表单元素,因为 DataTable 从 DOM 中删除了不可见的节点。