Javascript 创建';下载到CSV';Wordpress管理中PHP数组中的按钮

Javascript 创建';下载到CSV';Wordpress管理中PHP数组中的按钮,javascript,php,jquery,ajax,wordpress,Javascript,Php,Jquery,Ajax,Wordpress,我已经使用一个函数填充了一个多维PHP数组,我希望允许我的管理员用户下载内容 我找到了一个PHP函数,该函数应该允许我将数组导出到CSV并将其放入我的functions.PHP中,使用第二个函数将其连接到AJAX,并使用jQuery启动AJAX函数 有什么问题吗? 因此,我99%确信AJAX正确地发布到PHP函数,但由于某些原因,下载没有开始 我已经对此进行了很多研究,但仍在努力寻找解决方案——如果能找到正确的方向,我将不胜感激 // Function to generate download

我已经使用一个函数填充了一个多维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)
        });

    });
});
下载CSV
jQuery(文档).ready(函数(){
jQuery(“#下载CSV”)。单击(函数(){
风险值数据={
action:'ajaxlaurafunction',//调用PHP函数-注意它必须连接到AJAX
inputarray:“”,//发送要在PHP函数中使用的变量
};
//这是以下内容的缩短版本:https://api.jquery.com/jquery.post/
jQuery.post(“”,数据,函数(){
//window.location.replace(location.pathname)
});
});
});

根据@charlietfl的建议,我发现“您无法通过Ajax实现,因为JavaScript无法将文件直接保存到用户的计算机上(出于安全考虑)。”

替代解决方案

我的替代解决方案是使用“post方法”设置post参数

// Form on Page 
<form method="post" id="download_form" action="">
    <input type="submit" name="download_csv" class="button-primary" value="Download CSV" />
</form>

ajax和下载是不同的概念。在搜索中使用这两个术语做一些研究charlietfl-OK。谢谢你的指点@用户8262086。谢谢:)。我现在发布了一个不使用AJAX的解决方案。我对你的评论很感兴趣。你会用什么动作钩让它在前端工作?对于想要DL数据集的用户?@user1518699尝试“init”。这是一个很好的答案。这很好,用于导出我创建的自定义WP_列表。我做的几乎完全相同,但在wordpress前端页面上。当用户下载到csv文件时,他们的数据。但它确实会将页面代码塞进文件中,即使在我调用exit时也是如此。有什么想法吗?
add_action("admin_init", "download_csv");

function download_csv() {

if (isset($_POST['download_csv'])) {

    function outputCsv( $fileName, $assocDataArray ) {
        ob_clean();
        header( 'Pragma: public' );
        header( 'Expires: 0' );
        header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
        header( 'Cache-Control: private', false );
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename=' . $fileName );
        if ( isset( $assocDataArray['0'] ) ) {
            $fp = fopen( 'php://output', 'w' );
            fputcsv( $fp, array_keys( $assocDataArray['0'] ) );
            foreach ( $assocDataArray AS $values ) {
                fputcsv( $fp, $values );
            }
            fclose( $fp );
        }
        ob_flush();
    }

    // This is dummy data. 

    $data = array(
        array( 'item' => 'Server', 'cost' => 10000, 'approved by' => 'Joe' ),
        array( 'item' => 'Mt Dew', 'cost' => 1.25, 'approved by' => 'John' ),
        array( 'item' => 'IntelliJ IDEA', 'cost' => 500, 'approved by' => 'James' ),
    );


    outputCsv( 'expenses.csv', $data );

    exit; // This is really important - otherwise it shoves all of your page code into the download

}

}