Django / Jquery GET请求下载csv文件

时间:2018-05-25 17:44:20

标签: python jquery ajax django

我正在寻找与python / jquery相关的答案,但到目前为止我还没有幸运!

我正在尝试通过AJAX GET调用下载服务器发送的csv文件。我可以通过blocking-get请求成功下载它,但我想通过ajax实现相同的功能。

Python / Django View

    header = None
    rows = []
    for student in students:
        if not header:
            header = get_header()
            rows.append(header)
        rows.append([student.id, student.name, student.marks])
    buf = StringIO()
    writer = csv.writer(buf)
    for row in rows:
        writer.writerow(row)
    response = HttpResponse(buf.getvalue(), content_type='text/csv')
    response['Content-Disposition'] = 'attachment'
    return response

AJAX GET请求

<script>
    $(document).ready(function () {
        $('#download-grades').on('click', function (event) {
            event.preventDefault();
            var grades_csv_url = $(event.target).data().url
            $.ajax({
                url: grades_csv_url,
                type: 'GET',
                // dataType: 'text/csv; charset=utf-8',
                success: function (response, status, xhr) {
                    console.log('-')
                },
                error: function (jqXHR) {
                    console.log(jqXHR.responseText); // the response is always received in error not in success.
                }
            });
        });
    })

</script>

接下来是什么?

我想在收到csv响应时开始下载文件。

2 个答案:

答案 0 :(得分:1)

您是否尝试在javascript中设置此项而不是创建ajax?

document.location = grades_csv_url

答案 1 :(得分:0)

您可以在js中将文本响应转换为csv:

var element = document.createElement('a');
element.href = 'data:text/csv;charset=utf-8,' + encodeURI(response);
element.target = '_blank';
element.download = 'csv_data.csv';
element.click();