如何在特定按钮上下载带有Javascript和AJAX的csv文件?
我正在用PHP生成一个CSV字符串,并通过AJAX将其发送到我的Javascript函数 一个简单的按钮如何在特定按钮上下载带有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
<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语法有效)