javascript - 在 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: '"Auftragsdatum","OrderNo","ReferenceOrder","Pos","Quantity","ArtNo","ManufactureNo","ProductName","ReferencePosition","NetPerPiece","InvoiceNo","DeliveryNoteNo","SerialNumbers","Manufacturer","CI","Type","Import_ID","State","Supplier","NetPerPieceSale","OU","Modified_Date","Added_by","Modified_by","isSupplier","isManufacturer"\\n"01.04.2019","7027856072","a","100","1","2099882","GS1900-24HP-EU0101F","ZYXEL GS1900-24HP 24P GbE L2 PoE Switch","CLINO","251,09","950347427","6054042579","S182L37002129","ZYXEL","sel","","","716","ALSO","","OU00100","11-11-2019 09:58","admin","","","BPT07939"\\n"01.04.2019","7027856072","bg","200","1","3074862","EAP225 V3","TP-LINK AC1350 WLAN Dual Band Gigabit AP","CLINO","64,56","950347427","6054042579","218B410001725","TP-LINK","sel","","","716","ALSO","","OU00100","11-11-2019 09:58","admin","","","BPT07134"\\n"01.04.2019","7027856072","cd","300","1","7003581","","Mautgebühr","nan","2,09","950347427","6054042579","","","sel","","","716","ALSO","","sel","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);
解决方案
看来您是一些将表格数据转换为 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)
推荐阅读
- python - 在 Django 中自定义表单验证错误显示
- awk - 打印=之后的所有内容
- python - 如何在txt中下载图片url?
- python - 在训练和测试数据集中加载图像时获得许可被拒绝
- c# - ListView 中的标签未绑定到 Collection Clear
- php - 无法在库 codeigniter 中实例化抽象类
- jekyll - 如何在 Jekyll 中将 csv 文件的文件夹转换为 json 文件
- python-3.x - LSTM 的预期隐藏状态维度没有考虑批量大小
- javascript - Webpack:使用一个条目生成多个输出
- python - 这两种计算文本列中两个单词出现次数的方法有什么区别?