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.

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组