Wordpress 自定义帖子类型 csv 导出器

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

我正在尝试使用 Ajax 导出自定义后类型数据 csv 格式,但它导出一个空白的 csv 文件,但是当我在 js 控制台上看到它时,它会显示所有数据,如屏幕截图

请帮我解决问题

这是 PHP 代码,它只是在模态中使用 ajax 提取自定义 posttype 数据

 public function export_result_entry_csv(){


  $data = $_POST['data'];
  $args = [
   'post_type' => 'student',
   'posts_per_page'=> -1,
   'meta_key' => 'student_roll_number',
   'orderby' => 'meta_value_num',
   'order' => 'ASC',
   'tax_query' => [
       [
           'taxonomy' => 'year',
           'terms' => $data['year'],
           'field' => 'slug',
           'operator' => 'IN'
           ]
   ],
   'meta_query'    => [
       'relation' => 'AND',
       [
           'key'       => 'wp_sr_student_main_subject',
           'value'     => $data['subject'],
           'compare'   => 'LIKE',
       ],
       [
           'key'       => 'wp_sr_student_class',
           'value'     => $data['class'],
           'compare'   => 'LIKE',
       ]
   ]

];
$query = new \WP_Query($args);  
$delimiter = ","; 
$filename = "members-data_" . date('Y-m-d') . ".csv"; 
$f = fopen('php://memory', 'w'); 
$fields = array('ID', 'FIRST NAME', 'CREATED'); 
fputcsv($f, $fields, $delimiter); 

while($query->have_posts())  : $query->the_post();
$lineData = array(get_the_ID(), get_the_title(), get_the_time()); 
fputcsv($f, $lineData, $delimiter); 

endwhile;

fseek($f, 0); 
     
// Set headers to download file rather than displayed 
header('Content-Type: text/csv'); 
header('Content-Disposition: attachment; filename="' . $filename . '";'); 
 
//output all remaining data on a file pointer 
fpassthru($f); 

   wp_die();
 }

Js 代码

jQuery(function($){
    "use strict"
    $(document).on('click', '.esrp-export-entry', function(e){
        e.preventDefault();
        var data = {
            'action': 'export_result_entry_csv',
            '_wpnonce': esrp_data._nonce,
            'data' : $(this).parents('.show-mark-entry-form').siblings('.wsr-result-generate').data('info')
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(esrp_data.ajaxurl, data, function(response) {
            let url = ajaxurl+'?action=export_result_entry_csv';
             console.log(url);
             let a = document.createElement('a');
                a.href = url;
                a.download = 'export.csv';
                document.body.appendChild(a);
                a.click();
                a.remove();
          
           console.log(response)
        
           //display the created CSV data on the web browser 
           $('.downlaod').html(response);
        });
    });
});  

哪里错了???谁能帮帮我???

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