我试图制作一个带有按钮的插件,该按钮导出为excel一个列表。
现在我有了插件的索引,它在桌面上显示了列表,在顶部显示了按钮。这是代码:
ajax调用总是返回0,即使我删除了代码并放入了#echo;#34; hello"在exportplassere_callback ...
function exportplassere_callback(){
require_once plugins_url('libs/PHPExcel.php', __FILE__);
global $wpdb;
$email_list = $wpdb->get_results('
SELECT email, estado, fecha
FROM subscribers
ORDER BY fecha');
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Prueba')
->setCellValue('B2', 'Prueba!')
->setCellValue('C1', 'Prueba')
->setCellValue('D2', 'Prueba!');
$objPHPExcel->getActiveSheet()->setTitle('Prueba');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Prueba"'); //nombre del archivo que se descarga
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
function altimea_export_page() {
global $wpdb;
add_action( 'wp_ajax_exportplassere', 'exportplassere_callback' );
$email_list = $wpdb->get_results('
SELECT email, estado, fecha
FROM subscribers
ORDER BY fecha');
?>
<div class="wrap">
<div class="container">
<div class="header col-xs-12 col-sm-12">
<h3>Exportar suscriptores - Plassere</h3>
</div>
<div class="col-xs-12 col-sm-12">
<form id="ajax_form" method="post">
<button type="submit" class="btn btn-primary">EXPORTAR</button>
</form>
<table data-toggle="table" data-show-toggle="true" data-show-columns="true" data-select-item-name="toolbar1" data-pagination="true" data-sort-name="fecha" data-sort-order="desc">
<thead>
<tr>
<th data-sortable="true">Email</th>
<th data-sortable="true">Fecha</th>
<th data-sortable="true">Estado</th>
</tr>
</thead>
<tbody>
<?php
foreach ($email_list as $suscriber) { ?>
<tr>
<td><?php echo $suscriber->email; ?></td>
<td><?php echo date('d-m-Y', strtotime($suscriber->fecha)); ?></td>
<td><?php echo $suscriber->estado; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#ajax_form').bind('submit', function(e) {
e.preventDefault();
var data = {
'action': 'exportplassere',
'value': 'prueba'
};
$.post(ajaxurl, data, function(response) {
console.log(response);
});
});
});
</script>
<?php } }
答案 0 :(得分:0)
每当你在Wordpress中使用ajax时,你应该总是在function 'or the action'
的末尾声明die(),它返回ajax数据。如果您未说明die();
,则0
将作为输出发送回您的脚本。
这就是为什么ajax调用总是返回0
,即使你回复某种类似hello
的字符串。
因此,在您的情况下,您应该在行动结束时die();
陈述exportplassere_callback
,即返回您的ajax数据的函数。
您需要在die();
之后立即说明$objWriter->save('php://output');
:
$objWriter->save('php://output');
die();
}