首页 > 解决方案 > 在 JS 中生成 csv 并使用 ajax 请求 POST 将其发送到烧瓶

问题描述

我正在尝试使用我的代码在 JS 中创建一个 CSV 文件table2csv。然后我想使用 ajax 请求将它发送到烧瓶并再次返回给客户端。

但是当我尝试将文件发送到服务器时,它会返回 ajax 找不到我的文件的错误。

我使用console.log 检查我的文件是否已创建。我被卡住了,不知道该怎么办了,因为我对 ajax 请求很陌生,所以任何帮助都会很棒。

这是我的 JS 部分,也是我目前正在做的事情:

//On Update click renders table to csv, activates the be_filter and reopens it in the filtered_file.html
var isClicked;
jQuery("#update").on('click', function(){
    var response = confirm('Are you sure you want to UPDATE rows ?');
    if(response == true){
        isClicked = $('#my_id').table2csv();
        $.ajax({
            type:'POST',
            url:"{{url_for('update_file')}}",
            data: {'data': isClicked},
            success: function(result){
                console.log(result);
            },
            error: function(error){
                console.log(JSON.stringify(error));
            }
        });event.preventDefault();
         //window.location.href='/update_file';
    }else{
        return false;
    }
});

烧瓶调用:

@app.route('/update_file', methods=['GET', 'POST'])
@login_required
def update_file():
    '''Opens the filtered_file page but with updated file'''
    clicked = None
    if request.method == 'POST':
        clicked = request.form['data']
        file_to_filter = pd.read_csv(clicked, sep=';', engine='python', encoding='utf_8_sig')
        table1 = update_csv(file_to_filter)
        table2 = table1.to_html(classes='my_class" id = "my_id')
        return render_template('3_filtered_file.html', data=table2)

编辑: console.log() 的错误消息:

POST http://127.0.0.1:5000/update_file 500 (INTERNAL SERVER ERROR)


{"readyState":4,"responseText":"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n  \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n  <head>\n    <title>FileNotFoundError: [Errno 2] No such file or directory: '&quot;Auftragsdatum&quot;,&quot;OrderNo&quot;,&quot;ReferenceOrder&quot;,&quot;Pos&quot;,&quot;Quantity&quot;,&quot;ArtNo&quot;,&quot;ManufactureNo&quot;,&quot;ProductName&quot;,&quot;ReferencePosition&quot;,&quot;NetPerPiece&quot;,&quot;InvoiceNo&quot;,&quot;DeliveryNoteNo&quot;,&quot;SerialNumbers&quot;,&quot;Manufacturer&quot;,&quot;CI&quot;,&quot;Type&quot;,&quot;Import_ID&quot;,&quot;State&quot;,&quot;Supplier&quot;,&quot;NetPerPieceSale&quot;,&quot;OU&quot;,&quot;Modified_Date&quot;,&quot;Added_by&quot;,&quot;Modified_by&quot;,&quot;isSupplier&quot;,&quot;isManufacturer&quot;\\n&quot;01.04.2019&quot;,&quot;7027856072&quot;,&quot;a&quot;,&quot;100&quot;,&quot;1&quot;,&quot;2099882&quot;,&quot;GS1900-24HP-EU0101F&quot;,&quot;ZYXEL GS1900-24HP 24P GbE L2 PoE Switch&quot;,&quot;CLINO&quot;,&quot;251,09&quot;,&quot;950347427&quot;,&quot;6054042579&quot;,&quot;S182L37002129&quot;,&quot;ZYXEL&quot;,&quot;sel&quot;,&quot;&quot;,&quot;&quot;,&quot;716&quot;,&quot;ALSO&quot;,&quot;&quot;,&quot;OU00100&quot;,&quot;11-11-2019 09:58&quot;,&quot;admin&quot;,&quot;&quot;,&quot;&quot;,&quot;BPT07939&quot;\\n&quot;01.04.2019&quot;,&quot;7027856072&quot;,&quot;bg&quot;,&quot;200&quot;,&quot;1&quot;,&quot;3074862&quot;,&quot;EAP225 V3&quot;,&quot;TP-LINK AC1350 WLAN Dual Band Gigabit AP&quot;,&quot;CLINO&quot;,&quot;64,56&quot;,&quot;950347427&quot;,&quot;6054042579&quot;,&quot;218B410001725&quot;,&quot;TP-LINK&quot;,&quot;sel&quot;,&quot;&quot;,&quot;&quot;,&quot;716&quot;,&quot;ALSO&quot;,&quot;&quot;,&quot;OU00100&quot;,&quot;11-11-2019 09:58&quot;,&quot;admin&quot;,&quot;&quot;,&quot;&quot;,&quot;BPT07134&quot;\\n&quot;01.04.2019&quot;,&quot;7027856072&quot;,&quot;cd&quot;,&quot;300&quot;,&quot;1&quot;,&quot;7003581&quot;,&quot;&quot;,&quot;Mautgebühr&quot;,&quot;nan&quot;,&quot;2,09&quot;,&quot;950347427&quot;,&quot;6054042579&quot;,&quot;&quot;,&quot;&quot;,&quot;sel&quot;,&quot;&quot;,&quot;&quot;,&quot;716&quot;,&quot;ALSO&quot;,&quot;&quot;,&quot;sel&quot;,&quot;11-11-2019 ...

编辑 2 ** 这是我的 **table2csv 代码

(function ($) {
const _trim_text = (text) => {
    return text.trim();
};
const _quote_text = (text) => {
    return '"' + text + '"';
};

function convert(tb){
    let output = "";
    let lines = [];

    $(tb).find('thead>tr').each(function () {
        let line = [];
        $(this).find('th:not(th:eq(0))').each(function () { 
            line.push(_quote_text(_trim_text($(this).text())));
        });
        lines.push(line.splice(0).toString());
    })

    $(tb).find('tbody>tr').each(function () {
        let line = [];
        $(this).find('td').each(function () {   
            if($(this).find('select').length){
                line.push(_quote_text($(this).find('option:selected').val()));
            }else if($(this).find('input').length){
                line.push(_quote_text($(this).find('input').val()));
            }
            else
            line.push(_quote_text(_trim_text($(this).text())));
        });
        lines.push(line.splice(0).toString());
    })
    output = lines.join('\n');
    return output;
};

$.fn.table2csv =  function () {
    let csv = convert(this);
    //cases = $('#out').append($("<pre>").text(csv));   
    return csv;
};

})(jQuery);

标签: javascriptpythonajaxflask

解决方案


看来您是一些将表格数据转换为 csv 的 jQuery 插件。它实际上并没有在您的磁盘上创建文件。当您向服务器发出 ajax POST 请求时,您正在发送表单数据。在服务器端,您在clicked = request.form['data']此处单击的不是文件。但是您的熊猫read_csv需要 url 或缓冲区类型。您可以使用StringIO.

@app.route('/update_file', methods=['GET', 'POST'])
@login_required
def update_file():
    '''Opens the filtered_file page but with updated file'''
    clicked = None
    if request.method == 'POST':
        clicked = StringIO(request.form['data'])
        file_to_filter = pd.read_csv(clicked, sep=';', engine='python', encoding='utf_8_sig')
        table1 = update_csv(file_to_filter)
        table2 = table1.to_html(classes='my_class" id = "my_id')
        return render_template('3_filtered_file.html', data=table2)

推荐阅读