我使用https://datatables.net/examples/api/select_row.html中的代码来选择多行
this.props.history.replace('/...');
这是jquery数据表的初始化
$('#table tbody').on('click','tr', function(){
$(this).toggleClass('selected');
});
现在我想通过ajax调用将这些选定的行发送到php控制器,这样我就可以用这些选定的行数据创建一个csv文件。
我创建了一个按钮,在点击时调用以下函数进行ajax调用
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
dom: 'Bfrtip',
buttons: [
//'copyHTML5', 'csvHTML5', 'excelHTML5', 'pdfHTML5', 'printHTML5'
'copy', 'csv', 'print'//, 'excel', 'pdf'
],
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('person/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
{
"targets": [ -2 ], //2 last column (photo)
"orderable": false, //set not orderable
},
],
});
$('#table tbody').on('click','tr', function(){
$(this).toggleClass('selected');
});
}
当我从控制器执行 function create_PO()
{
$('#btnSel').text('creating...');
$('#btnSel').attr('disabled',true);
var url = "<?php echo site_url('person/create_csv')?>";
var selectedData = table.rows('.selected').data();
//console.log(selectedData);
//alert(selectedData.length);
newData = new Array();
for(i=0;i<selectedData.length;i++){
newData.push(selectedData[i]);
}
jsonData = JSON.stringify({data : (selectedData[0].slice(0,5))});
//console.log(jsonData);
//newData = $.serialize(newData);
//console.log(newData);
$.ajax({
url : url,
type: "POST",
data: jsonData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data)
{
/*data.forEach(function(e){
console.log(e);
})*/
console.log(data);
// alert("sheet created successfully");
// $('#btnSel').text('create');
// $('#btnSel').attr('disabled',false);
},
/*error: function (jqXHR, textStatus, errorThrown)
{
alert('Error creating file');
}*/
});
}}
时,响应显示为空数组。
此外,ajax的成功echo($_POST)
功能选项也不会打印任何内容。任何人都可以告诉我这是什么问题?谢谢!
答案 0 :(得分:1)
您在控制台中没有得到任何内容的原因是success
回调获取服务器返回的数据,而不是发送的数据。试试console.log(jsonData)
。
此外,要分析发送的数据,请使用Chrome开发者工具上的“网络”标签。
在PHP方面,您可能在请求有效负载中传递数据,这是因为您的表单是JSON类型,而不是Content-Type: application/x-www-form-urlencoded
要访问它,请使用以下代替$_POST
:
$data = file_get_contents('php://input');
将字符串化的json处理为数组:
$processedData = json_decode($data);
现在您可以像这样访问您的数组属性:
foreach($processedData as $item){
// do stuff
echo $item;
}