jQuery 下载带有链接 onclick 的 csv 文件

问题描述 投票:0回答:2

我正在尝试使用 jquery 按钮 onclick 下载 CSV 文件。我有一个 id 为

<a>
export
标签,我希望它指向下载链接,我可以在其中下载刚刚创建的 CSV 文件。

// Using this jquery to send my sql query to server-side-CSV
$('#export').on('click', function() {
  var sqlsend = dataTable.ajax.json().sql;
  $.post('server-side-CSV.php', 'val=' + sqlsend, function(request){
    //code should go here
  });
});

这是我的 php 代码,我正在其中创建 CSV 文件

// This is my server-side-CSV file. It's creating a csv file to     downloaded
<?php
require("connection.php");
$sql = $_POST['val'];
.
.more code
.

// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
fclose($output);
exit;
?>

如何下载 CSV 文件?

编辑: 终于找到答案了

$('#export').on('click', function() {
  var sqlsend = dataTable.ajax.json().sql;
  window.location.href="server-side-CSV.php?val="+sqlsend;
});
javascript php jquery html csv
2个回答
0
投票

而不是

$.post
,将浏览器发送到下载位置:

document.location.href = 'server-side-CSV.php?val='+sqlsend;

您需要在循环之前添加标题。

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

0
投票

$('.btn-export').on('click',function(){
   $.ajax({
    url:"<?php echo admin_url('admin-ajax.php') ?>",
    type:"POST",
    data:{
        action:"export_news_cpt",
    },
    success:function(response)
    {
           if (response !== 0) {
                        Swal.fire({
                            icon: "success",
                            title: "Downloaded",
                            text: "Thankyou for downloading this file",
                        });
                        var link = document.createElement('a');
                        link.href = 'data:text/csv,' + encodeURIComponent(response);
                        link.download = 'news_data.csv';
                        link.click();

                    } else {
                        Swal.fire({
                            icon: "error",
                            title: response.data.message,
                            text: "Something went wrong!",
                        });
                    }
    },
    error : function (xhr , status,error)
    {
        alert("AJAX Response:"+error);
    },
    
   });

   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
add_action('wp_ajax_nopriv_export_data', 'export_data');
add_action('wp_ajax_export_data', 'export_data');
function export_data()
{
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $args = [
            'post_type' => 'book',
            'posts_per_page' => -1
        ];
        $query = new WP_Query($args);

        if ($query->have_posts()) {
            $csv = 'Post ID,Post Type,Post Title,Post DateTime,Book Author ,Publisher Name,Price,Genre,Post Thumbanil ';
            while ($query->have_posts()) {
                $query->the_post();
                $post = $query->post;
                $post_id = get_the_ID();
                $post_type = get_post_type();
                $post_title = get_the_title();
                $post_date_time = get_the_date() . '' . get_the_time();
                $post_book_author = get_post_meta($post_id, 'author_name', true);
                $post_publisher_name = get_post_meta($post_id, 'publisher_name', true);
                $post_book_price = get_post_meta($post_id, 'book_price', true);
                $post_book_genre = get_post_meta($post_id, 'book_genre', true);
                $post_thumbnail_url = get_the_post_thumbnail_url($post_id);


                $csv .= '"' . $post_id . '","' . $post_type . '","' . $post_title . '","' . $post_date_time . '","' . $post_book_author . '","' . $post_publisher_name . '","' . $post_book_price . '","' . $post_book_genre . '","' . $post_thumbnail_url . '"' . '"\n';
            }
            wp_reset_postdata();
            header("Content-type: text/csv");
            header("Content-Disposition: attachment; filename=file.csv");
            header("Pragma: no-cache");
            header("Expires: 0");
            echo $csv;
            exit;
        } else {
            echo 0;
        }
    } else {
        wp_send_json_error(array("message" => "REQUEST METHOD POST"));
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.