使用jQuery AJAX调用导出CSV

Export CSV using jQuery AJAX call

本文关键字:CSV 调用 jQuery AJAX 使用      更新时间:2023-09-26

我有一些代码将搜索结果导出到CSV文件:

$("#exportButton").click(function () {
    var url = "/Stuff/ExportSearchResults";
    var searchInput = readInput();
    $.post(url, searchInput, function (data) {
        // This is where I'm clueless.
        // I'm getting data back but not sure how to make the
        // browser show a prompt to download the file.
        console.log(data);
    });
});

在服务器端(ASP。. NET MVC 4)有这个:

[HttpPost]
public FileResult ExportSearchResults(SearchInput model)
{
    string csv = GenerateCsv(model);
    return File(new UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}

好的是我在控制台中得到了数据。我只是不确定如何让浏览器显示下载文件的提示。

对于这个问题,我们可以使用https://stackoverflow.com/users/5349021/sreepathy-sp

的注释。

客户端

$("#exportButton").click(function () {
       var url = "/Stuff/ExportSearchResults";
       var searchInput = readInput();
       window.location.href = '/Stuff/ExportSearchResults?searchInput='+searchInput ;
});

服务器端

[HttpGet]
public FileResult ExportSearchResults(string model)
{
    string csv = GenerateCsv(model);
    Stream stream = new MemoryStream(new UTF8Encoding().GetBytes(csv));
    return File(stream , "text/csv", "Export.csv");
}