无法将数据流从AJAX响应转换为CSV文件



我正在尝试将ajax响应转换为csv文件,这是一个带有一些垃圾字符的数据流(可能是blob或字节流或字节数组,不确定(。在下载的文件中,我也得到了同样的垃圾数据。

$.ajax({
url: requestUrl,
type: "POST",
async: false,
data: data_request_clientside,
contentType: 'application/json;charset=utf-8',
dataType: 'text',
success: function (response) {
var binary = "";
var responseTextLen = response.length;
for ( i = 0; i < responseTextLen; i++ ) {
binary += String.fromCharCode(response.charCodeAt(i) & 255);
}
var a = document.createElement('a');
a.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml;base64," + btoa(binary);
a.download = 'workingStuff.csv';
document.body.appendChild(a);
a.click();
a.remove();
},
error: function (error) {
console.log("Something went wrong", error);
}
}); 
var blob = new Blob([csvString]);
if (window.navigator.msSaveOrOpenBlob)  // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, "filename.csv");
else
{
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob, {type: "text/plain"});
a.download = "filename.csv";
document.body.appendChild(a);
a.click();  // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
document.body.removeChild(a);
}

只需将代码放在success函数下,并根据您的需要进行少量修改,这还没有经过测试

相关内容

  • 没有找到相关文章

最新更新