在wordpress中我想使用ajax生成csv文件。因此,基本上当用户点击按钮时它会进行ajax调用,而在ajax php文件中它会生成csv并将其下载到用户系统。所以为此我完成了我的代码
我的标记就像这样
<button type="button" class="btn export-csv" data-proj-id="1">Export CSV</button>
js代码就像这样
$('body').on('click', 'button.export-csv', function() {
var proj_id = $(this).attr('data-proj-id');
$.ajax({
type:"POST",
url:trans.ajaxUrl,
data:'proj_id='+proj_id+'&action=export_client_price_csv',
success: function (data) {
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(data);
location.href = uri;
}
});
});
我的php代码看起来像这样
function export_client_price_csv() {
global $wpdb;
$proj_id = $_POST['proj_id'];
$user_id = get_current_user_id();
$site_id = get_current_blog_id();
if( !empty($proj_id) ) {
$get_prices_data = $wpdb->get_results("SELECT * FROM `fl_client_price` WHERE `user_id` = ".$user_id." AND
`project_id` = ".$proj_id." AND `site_id` = ".$site_id." AND `client_status` LIKE '%invoiced%' ");
$data_array = array();
if( count($get_prices_data) > 0 ) {
foreach( $get_prices_data as $data ) {
$array = get_object_vars($data);
array_push($data_array, $array);
convert_to_csv($data_array, 'report.csv', ',');
}
}
}
exit;
}
add_action( 'wp_ajax_export_client_price_csv', 'export_client_price_csv' );
function convert_to_csv($input_array, $output_file_name, $delimiter)
{
/** open raw memory as file, no need for temp files, be careful not to run out of memory thought */
$f = fopen('php://memory', 'w');
/** loop through array */
foreach ($input_array as $line) {
/** default php csv handler **/
fputcsv($f, $line, $delimiter);
}
/** rewrind the "file" with the csv lines **/
fseek($f, 0);
/** modify header to be downloadable csv file **/
header('Content-Type: text/html; charset=UTF-8');
//header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
/** Send file to browser for download */
fpassthru($f);
}
当我点击按钮时,它正在下载文件,但没有扩展名.csv。我不知道这里发生了什么。 有人能告诉我如何解决这个问题吗?
答案 0 :(得分:0)
似乎无法使用 location.href 或 window.location.href 指定filename.extension。
如果您模拟锚点,则可以指定filename.extension:
var csvdata = "Hello World"; // only for test
var byteNumbers = new Uint8Array(csvdata.length);
for (var i = 0; i < csvdata.length; i++)
{
byteNumbers[i] = csvdata.charCodeAt(i);
}
var blob = new Blob([byteNumbers], {type: "text/csv"});
// Construct the uri
var uri = URL.createObjectURL(blob);
// Construct the <a> element
var link = document.createElement("a");
link.download = 'myfile.csv';
link.href = uri;
document.body.appendChild(link);
link.click();
// Cleanup the DOM
document.body.removeChild(link);
delete link;
参见此处:how to specify csv file name for downloading in window.location.href