javascript - python flask : How to handle send_file on the client side

标签 javascript jquery python flask savefiledialog

我使用 xlwt 和 StringIO 根据客户端给出的输入在服务器端生成了一个 excel 文件。现在我想将文件发送回客户端,以便他/她可以保存它(最好使用保存对话框)。

我正在尝试使用 send_file 来做到这一点,但由于我不太擅长 javascript/jquery/ajax,所以我实际上不知道如何在客户端处理这个问题。根据下面的代码(主要从 Flask 主页收集),你能给我一个如何到达那里的提示吗?

感谢您的帮助!

代码如下:

请注意:JS 代码是由按钮上的单击事件触发的。当将 json 从客户端传递到服务器并返回时它工作正常...

Python

import StringIO
import wordpuzzle # The code that creates the excel file

@app.route('/_create_wordsearch')
def create_wordsearch():

    wordlist = json.loads(request.args.get('wordlist'))

    # create a stringIO object
    output = StringIO.StringIO()

    # Instantiate the PuzzleGrid class
    p = wordpuzzle.PuzzleGrid(wordlist)

    # Create the Puzzle
    p.main()

    # Create the xls file in memory
    p.output2excel(output)

    # Set back to start
    output.seek(0)

    # send back to client
    return send_file(output, mimetype='application/vnd.ms-excel')

JS

$(document).ready(function() {
    $("#create_btn").bind('click', function(){
        //Get all words from list
        var list = [];
        $("#wordlist option").each(function(){
            list.push($(this).val());
        });
        $.getJSON($SCRIPT_ROOT + '/_create_wordsearch', {
            wordlist: JSON.stringify(list)
        }, function(data){
            // What goes in here?
        });
        return false;
    });
});

最佳答案

假设页面上有一个 div 用作目标:

<div id="exportdiv"></div>

将 $.getJSON 调用替换为如下代码:

var url = $SCRIPT_ROOT + '/_create_wordsearch';

// hide the div, write the form
$('#exportdiv').hide()
    .html('<form id="exportform" action="' + url + '" target="_blank" method="get">'
        + '<textarea name="wordlist">' + JSON.stringify(list) +'</textarea>'
        + '</form>');

// submit the form
$('#exportform').submit();

在服务器端,您需要对 JSON 进行转义。我不确定你是否可以喂Markup.unescape()直接进入 json.loads 但它会是这样的:

wordlist = json.loads(Markup(request.args.get('wordlist')).unescape())

关于javascript - python flask : How to handle send_file on the client side,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23978927/

相关文章:

javascript - 使用 json 填充 javascript.datatables?

javascript - keydown 上的 jQuery 下拉 ajax 搜索是 'one step behind'

python - 如何在 Python 中获取函数(及其模块)的名称?

python - python 中意外的关键字参数单击

javascript - html 是否在同一个对象上使用相同的 id

javascript - 如何使 <hr> 标签的行位于 <h> 标签的正下方?

javascript - 将 Cookie 添加到输入背景颜色更改

javascript - 根据已输入的内容调整输入字段的大小

python - selenium:socket.error: [Errno 61] 连接被拒绝

javascript - c3 图表工具提示不移动