javascript - jQuery 下载带有链接 onclick 的 csv 文件

标签 javascript php jquery html csv

我正在尝试使用 jquery 按钮 onclick 下载 CSV 文件。我有一个<a>标签 ID export我希望它指向下载链接,我可以在其中下载刚刚创建的 CSV 文件。

// Using this jquery to send my sql query to server-side-CSV
$('#export').on('click', function() {
  var sqlsend = dataTable.ajax.json().sql;
  $.post('server-side-CSV.php', 'val=' + sqlsend, function(request){
    //code should go here
  });
});

这是我的 php 代码,我正在其中创建 CSV 文件

// This is my server-side-CSV file. It's creating a csv file to     downloaded
<?php
require("connection.php");
$sql = $_POST['val'];
.
.more code
.

// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
fclose($output);
exit;
?>

如何下​​载 CSV 文件?

编辑: 终于找到答案了

$('#export').on('click', function() {
  var sqlsend = dataTable.ajax.json().sql;
  window.location.href="server-side-CSV.php?val="+sqlsend;
});

最佳答案

而不是$.post,将浏览器发送到下载位置:

document.location.href = 'server-side-CSV.php?val='+sqlsend;

您需要在循环之前添加 header 。

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

参见this answer .

关于javascript - jQuery 下载带有链接 onclick 的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40591536/

相关文章:

javascript - 使用 Login with Amazon 时遇到问题

javascript - 打开前查找 jQueryUI 对话框大小

php - 仅删除选项不起作用 PHP CRUD

javascript - 使用 selenium 抓取 Tripadvisor 时如何单击 "More"按钮?

javascript - ng-bind-html 不适用于脚本

php - JSON 意外的 token

php mysql..无法将变量分配给数据库中的字段名称

javascript - 导航 100% 分布在一个 div 中,填充均匀

javascript - 将 Javascript 变量传递给 Objective-C

javascript - 使用 event.preventDefault() 后导航不起作用