我创建了下面的代码,它接受一个JSON对象并将其转换为通过ConvertToCSV函数分隔的逗号。我的问题是如何将变量csvData作为csv文件下载?
此代码已经在按钮单击
上执行的功能中 var jsonObject = JSON.stringify(data);
var toCSV = ConvertToCSV(jsonObject);
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(toCSV);
答案 0 :(得分:3)
使用blob在本地存储然后下载它。例如
http://jsfiddle.net/koldev/cw7w5/
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
此http://jsfiddle.net/e5ggkkur/1/将在firefox中运行