简体   繁体   English

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

[英]How to download a csv file with Javascript and AJAX on a specific button?

I am generating a CSV string with PHP and send it via AJAX to my Javascript function. 我正在用PHP生成CSV字符串,并通过AJAX将其发送到我的Javascript函数。

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. 调用该函数,然后应从字符串中下载CSV文件。 How can I handle that? 我该如何处理?

My PHP Function 我的PHP函数

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,\n";

// 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']."\n";
    }
  }
}

return $csv;

} }

returns a valid csv string like that "a,b,c,d" . 返回有效的csv字符串,例如"a,b,c,d"

My Javascript looks like: 我的Javascript如下:

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. 在回调中,我想将this.responseText下载为CSV文件。 Is that possible? 那可能吗?

Instead of console.log in ajax onreadystatechange handler call this function 而不是ajax onreadystatechange处理程序中的console.log调用此函数

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM