// Function to generate download 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: application/csv' ); header( 'Content-Disposition: attachement; filename="' . $output_file_name . '";' ); /** Send file to browser for download */ fpassthru( $f ); }
jQuery(document).ready(function () { jQuery('#downloadcsv').click(function () { var data = { action: 'ajaxlaurafunction', // Calls PHP function - note it must be hooked to AJAX inputarray: '', // Sends a variable to be used in PHP function }; // This is a shortened version of: https://api.jquery.com/jquery.post/ jQuery.post("", data, function () { //window.location.replace(location.pathname) }); }); });
解决方法:
继@charlietfl建议后,我发现“你不能通过Ajax来实现,因为Javascript无法将文件直接保存到用户的计算机上(出于安全考虑).– According to this post”