简体   繁体   English

WordPress 使用 Ajax 将表导出为 csv

[英]WordPress Export table as csv using Ajax

i'm trying to export my plugin table in the same page.我正在尝试在同一页面中导出我的插件表。 i tried to do hidden iframe but it still does not work我试图做隐藏的 iframe 但它仍然不起作用

PHP: PHP:

add_action( "wp_ajax_export_plugin", "export_plugin" );   //update_records is action
add_action( "wp_ajax_nopriv_export_plugin", "export_plugin" );

function export_plugin(){
  global $wpdb;
   $wpdb->show_errors = TRUE;
   $wpdb->suppress_errors = FALSE;

  

      
      $plugin_name = $_POST['plugin-name']; // PLUGIN NAME
      $plugin_export_type = $_POST['export-type']; // PLUGIN EXPORT TYPE as CVS/SQL/XML
  
      $plugin_name; // ?? not defined in original code
      $results = $wpdb->get_results("SELECT * FROM `wp_myplugin`",ARRAY_A);
    
    
    
      $csv_output = '"'.implode('";"',array_keys($results[0])).'";'."\n";;
    
      foreach ($results as $row) {
        $csv_output .= '"'.implode('";"',$row).'";'."\n";
      }
      $csv_output .= "\n";
    
      $filename = $plugin_name."_".date("Y-m-d_H-i",time());
      header("Content-type: application/force-download");
      header("Content-disposition: csv" . date("Y-m-d") . $plugin_export_type);
      header( "Content-disposition: filename=".$plugin_name.$plugin_export_type);
      header('Content-Description: File Transfer');

      echo $filename;
      exit;


}

AJAX JQUERY: AJAX 查询:

success:function(data){
            
     $('#ifram_download').src="/app?download=1&filename=" + data + '.csv';
}

Instead of echoing the filename, echo the file contents.不是回显文件名,而是回显文件内容。

<?php
echo $csv_output;
exit;

An alternative is to not use Ajax.另一种方法是不使用 Ajax。 Simply navigate to the Ajax URL via a link只需通过链接导航到 Ajax URL

<a href="<?php echo admin_url( 'admin-ajax.php' ); ?>?action=myexport">Export</a>

As the file is force downloaded the the url of the browser will remain the same.由于文件被强制下载,浏览器的 url 将保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM