dtfo55908 2018-01-21 00:09
浏览 50
已采纳

如何在特定按钮上使用Javascript和AJAX下载csv文件?

I am generating a CSV string with PHP and send it via AJAX to my Javascript function.

A simple button

<button id="download" type="button" onclick="csvExport()" name="button">CSV</button>

Call that function and should download a CSV file from the string. How can I handle that?

My PHP Function

function exportCSV(){
$profs = $this->getAllDozent();
$profs = json_decode($profs, true);
$currentID = 0;
$csv = "IDDOZENT,IDVERANSTALTUNG,BEZEICHNUNG,SWS,CREDITS,HAEUFIGKEIT_PA,FAKTOR_DOPPELUNG,SOMMER,WPF,KOSTEN_PA,
";

// Iteriere durch Professor Array
foreach($profs as $key => $value){
  $currentID = $value['IDDOZENT'];

  //Hole für ID die Veranstaltungen
  $veranstaltungen = $this->getVeranstaltungenByID($currentID);
  $veranstaltungen = json_decode($veranstaltungen, true);

  //Nur wenn Veranstaltungen da sind, abrufen.
  if($veranstaltungen != "NULL"){
    foreach ($veranstaltungen as $key => $value) {
    $csv = $csv.$currentID.","
    .$value['IDVERANSTALTUNG'].","
    .$value['BEZEICHNUNG'].","
    .$value['SWS'].","
    .$value['CREDITS'].","
    .$value['HAEUFIGKEIT_PA'].","
    .$value['FAKTOR_DOPPELUNG'].","
    .$value['SOMMER'].","
    .$value['WPF'].","
    .$value['KOSTEN_PA']."
";
    }
  }
}

return $csv;

}

returns a valid csv string like that "a,b,c,d".

My Javascript looks like:

function csvExport(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200){ 
            console.log(this.responseText);
        }
    };
    xmlhttp.open("GET", "csvExport.php", true);
    xmlhttp.send();
}

In the callback, I want to download the this.responseText as a CSV file. Is that possible?

  • 写回答

1条回答 默认 最新

  • doulingzou1712 2018-01-21 00:36
    关注

    Instead of console.log in ajax onreadystatechange handler call this function

    function downloadAsFile(csv, fileName) {
      var file = new File([csv], fileName, { type: "text/csv" })
      var anUrl = window.URL.createObjectURL(file)
      var a = window.document.createElement('a');
      a.href = window.URL.createObjectURL(file)
      a.download = fileName;
      a.click();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图