使用jQuery发布后编写和下载csv


write and download csv after posting using jquery

我正在使用jquery $.post将HTML表数据作为json发布到服务器端,用于将整个表数据写入csv文件。 但这不是将 CSV 输出为用户可下载的。

我想弹出csv文件

(通常在我们下载文件时发生,你知道csv的保存或打开框)

客户端代码

//selectedData is having the data as json 
$.post('ajax/csv_download.php', { 
    selectedData: JSON.stringify(selectedData) 
}, function(html){  });

服务器端代码

   global $fh; 
   $fh = @fopen( 'php://output', 'w' );
   $post_data = json_decode($_POST['selectedData']);
   foreach ($post_data as $arr)
   {
     $val1 = $arr->val1  ;
     $val2 = $arr->val2 ;
     $val3 = $arr->val3 ;
     $val4 = $arr->val4 ;
     $val5 = $arr->val5 ;
      $out = array($val1,$val2,$val3,$val4,$val5);
       fputcsv($fh, $out);
      }
听起来您想在

php 中将"内容类型"设置为"文本/纯文本"后将 CSV 文件的内容写回浏览器。根据 Web 浏览器的配置方式,它将提示用户保存/打开文件。

<?php 
  $content="name,age,height,weight,gender"; 
  $file="persons.csv";
  header("Content-Type: text/plain"); 
  header("Content-disposition: attachment; filename=$file"); 
  header("Content-Transfer-Encoding: binary"); 
  header("Pragma: no-cache"); 
  header("Expires: 0");
  echo "$content";
?>