【发布时间】:2018-02-18 11:36:25
【问题描述】:
我使用函数填充了一个多维 PHP 数组,我希望允许我的管理员用户下载内容。
我找到了一个 PHP 函数,它应该允许我将数组导出为 CSV 并将其放入我的 functions.php,使用第二个函数将其连接到 AJAX 并使用 jQuery 来触发 AJAX 函数。
有什么问题?
所以我 99% 确定 AJAX 正确地发布到 PHP 函数,但由于某种原因,下载没有开始。
我对此进行了很多研究,但一直在努力寻找解决方案 - 非常感谢您指出正确的方向!
// 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 );
}
我已经使用另一个函数将它连接到 Wordpress AJAX
function laura_function() {
$input_array = $_POST["inputarray"];
convert_to_csv($input_array, 'output.csv', ',');
exit;
}
add_action('wp_ajax_nopriv_ajaxlaurafunction', 'laura_function');
add_action('wp_ajax_ajaxlaurafunction', 'laura_function');
我写了一个小的 jQuery 函数来在按钮点击时进行 AJAX 调用
<button type="button" id="downloadcsv">Download CSV</button>
<script>
jQuery(document).ready(function () {
jQuery('#downloadcsv').click(function () {
var data = {
action: 'ajaxlaurafunction', // Calls PHP function - note it must be hooked to AJAX
inputarray: '<?php echo $inputarray?>', // Sends a variable to be used in PHP function
};
// This is a shortened version of: https://api.jquery.com/jquery.post/
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function () {
//window.location.replace(location.pathname)
});
});
});
【问题讨论】:
-
ajax 和下载是不同的概念。在搜索中使用这两个词进行一些研究
-
charlietfl - 好的。感谢您的指点。 @用户8262086。谢谢 :)。我现在已经为这个答案发布了一个不使用 AJAX 的解决方案。我会对你的 cmets 感兴趣。
标签: javascript php jquery ajax wordpress