从阿贾克斯下载文件(之类的)文件、阿贾克斯

2023-09-10 13:23:20 作者:依赖式习惯丶

我在GSP这个AJAX调用:

I have this ajax call in my GSP:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: data,
    success: function() {
        alert("Success");
    }
});

这是code座从我的控制器操作:

This is code block from my controller action:

response.setHeader("Content-disposition", "attachment; filename=sample.csv")
response.contentType = "application/vnd.ms-excel"

def outs = response.outputStream
def cols = [:]

tickets.each() {
    outs << it.ticketNo + ";" + it.subject
    outs << "\n"
}

outs.flush()
outs.close()

我得到了我通过从视图中通过$就法数据门票列表。比我格式化数据为CSV,比我想导出数据,CSV文件,但没有任何反应。该数据被发送到客户端,但没有下载的内容处置没有文件的格式不正确。我在想什么? 我一直试图做这样的事情:

I get tickets list from data that I pass from view via $.Ajax method. Than I format that data as CSV and than I want to export that data as CSV file but nothing happens. The data is send to client but there is no file for download as content-disposition is not well formed. What am I missing? I've tried to do something like:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: aoData,
    dataType: 'text',
    success: function(result) {
        var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
        window.open(uri, 'tiketi.csv');
    }
});

和控制器中我产生纯字符串,但这种方式,我得到一个文件,而不扩展,它是不可接受的。

and in controller I generate plain string, but that way I get a file without extension which is unacceptable.

我怎样才能做到这一点?谢谢你。

How can I achieve this? Thank you.

推荐答案

您不需要通过Ajax来做到这一点。该页面将不会重定向文件下载。

You dont need to do it via ajax. The page will not redirect for file downloads.