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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?