Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在特定按钮上下载带有Javascript和AJAX的csv文件?_Javascript_Php_Ajax_Csv - Fatal编程技术网

如何在特定按钮上下载带有Javascript和AJAX的csv文件?

如何在特定按钮上下载带有Javascript和AJAX的csv文件?,javascript,php,ajax,csv,Javascript,Php,Ajax,Csv,我正在用PHP生成一个CSV字符串,并通过AJAX将其发送到我的Javascript函数 一个简单的按钮 <button id="download" type="button" onclick="csvExport()" name="button">CSV</button> } 返回一个有效的csv字符串,如“a、b、c、d” 我的Javascript看起来像: function csvExport(){ var xmlhttp = new XMLHttpReq

我正在用PHP生成一个CSV字符串,并通过AJAX将其发送到我的Javascript函数

一个简单的按钮

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

返回一个有效的csv字符串,如
“a、b、c、d”

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

在回调中,我想将
this.responseText
作为CSV文件下载。这可能吗?

而不是ajax onreadystatechange处理程序中的控制台.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();
}

调用此函数,而不是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();
}

杰出的参数csv可以是任意字符串。(希望在这种情况下CSV语法有效)非常好!参数csv可以是任意字符串。(在这种特殊情况下,希望CSV语法有效)