douyue1998 2014-04-10 14:12
浏览 124

如何将javascript ajax数据导出到csv? [重复]

This question already has an answer here:

What I want to do: 1,use Javascript ajax POST array to PHP; 2,use POST array to search result from mysql with PHP; 3,return search results with csv format, so user can save the file. I have accomplished part 1 and part 2, but I can't get csv file returned I use ajax to POST array data to PHP like this:

$(document).ready(function(){
$('#export').click(function(){
    var list = JSON.stringify(count);
    $.ajax({
        type: "POST",
        url: "exportDataColoniesNumber.php",
        data: {'data': list},
        success: function(response){
            alert(response);
        }
    });
});
});

And process the data in exportDataColoniesNumber.php, and the page is to return a csv file:

<?php
$data = json_decode($_POST['data']);
$last_key = end(array_keys($data));
$sql = "SELECT * FROM coloniesNumber WHERE ";
foreach ($data as $key => $value) {
    $sql .= "num='" . $value . ($key == $last_key ? "';" : "' OR ");
}

$con = DatabaseConnection::get()->connect();
mysql_query('set names utf8');
mysql_select_db('fish') or die('Could not select database');
$result = mysql_query($sql);

$lines = '';
while($row = mysql_fetch_array($result)) {
    $line = '';
    for($i = 0; $i < $fields; $i++) {
        $line .= $row[$i] . ",";
    }
    $lines .= trim($line) . "
";
}
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:csv".date("Y-m-d").".csv");
header("Content-disposition:filename=test.csv");
print "$lines";
?>

The alert(response) return csv data:

8,4008,11.267,fat,1,,
9,4009,12.022,thin,1,,
10,4010,11.356,thin,1,,
11,4011,10.873,thin,1,,
12,4012,11.017,thin,1,,
13,4013,11.301,thin,1,,

How can I get csv file returned ?

</div>
  • 写回答

1条回答 默认 最新

  • duanji1482 2014-04-10 14:47
    关注

    Personally i've created a PHP handler that exports to csv, make sure you have these headers

    header("Content-Disposition: attachment; filename=report.csv");
    header("Content-Type: text/csv");
    

    Then just echo your data, csv-formatted or use one of the many free csv classes that does that for you (just call a function with an Array as a parameter)

    Then make your form (asuming you have one) post to a hidden iframe of 1x1 pixels and set offscreen with css

    iframe { position: absolute; left: -9999px; }
    

    You should be all set, and the export will pop up - however, make sure the file is not big or your script takes a lot of time to complete - until then, the download won't show up.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?