python - Flask Jinja2 模板在按钮单击时重新加载生成的表
问题描述
我有一个通过烧瓶运行的应用程序,它将用于在我的云平台上自动配置服务器。
其中一个页面允许您上传电子表格,然后将其解析为交互式(可编辑)html <table>
。
填充表格后,填充的字段将被验证。如果任何字段无效,则字段的类会更改以突出显示最终用户需要编辑的位置。
然后有一个验证器按钮,它获取当前的 html 表并再次对其运行验证,效果很好。但是,它不会重新加载 html 表,因此由于类未更改,任何已被用户更改的无效字段仍会突出显示。
我需要在此处更改什么以确保刷新表格?
这是代码。
烧瓶:
# upload spreadsheet and validate
@app.route('/upload/', methods=['GET','POST'])
def upload():
# if a file is attempted to be uploaded, save file and parse it
if request.method == 'POST' and request.files:
f = request.files['file']
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
myexcel = os.path.join(app.config['UPLOAD_FOLDER'], f.filename)
myJson = exc.Parse(myexcel)
mySpreadsheet = spreadsheet.zip_list(myJson)
return render_template('upload2.html', spreadsheet=mySpreadsheet)
# if the validate button is clicked, validate and repopulate table:
elif request.method == 'POST' and not request.files:
data = request.get_json()
data = json.loads(str(data['rows']).replace("'",'"'))
# Test print. this prints the data as expected on click of the validate button
pprint(data)
mySpreadsheet = spreadsheet.zip_list(data)
return render_template('upload2.html', spreadsheet=mySpreadsheet)
else:
return render_template('upload2.html')
HTML表格:
(是的,这是一张巨大的桌子!)
<!-- bunch of table headers here -->
{% for row in spreadsheet %}
<tr class="{{ loop.cycle('color1', 'color2') }}">
{% for i in range(36) %}
{% if "-invalid" in row[i]|string %}
<td contenteditable="true" class="red table-editable">{{ row[i]|replace("-invalid", "") }}</td>
{% else %}
<td contenteditable="true" class="table-editable">{{ row[i] }}</td>
{% endif %}
{% endfor %}
{% endfor %}
HTML 验证:
<div class="container">
<button id="validate" value="validate" class="button" >Validate Spreadsheet</button>
</div>
jQuery/AJAX:
// on validate, send potentially updated table in json format to flask
$('#validate').click(function() {
var $table = $("table")
rows = [],
header = [];
$table.find("thead th").each(function () {
header.push($.trim($(this).text()));
});
$table.find("tbody tr").each(function () {
var row = {};
$(this).find("td").each(function (i) {
var key = header[i],
value = $(this).text();
row[key] = value;
});
rows.push(row);
});
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/upload/",
traditional: "true",
data: JSON.stringify({rows}),
dataType: "json"
});
});
所以 AJAX 将数据发送到烧瓶没有问题,但是当该elif
语句被拾取时,它似乎并没有用新数据重新渲染模板。
很抱歉发了这么长的帖子,提前感谢您的帮助!
解决方案
所以,正如你自己所说,整个问题可以用这句话来概括:
所以 AJAX 将数据发送到烧瓶没有问题,但是当那个 elif 语句被拾取时,它似乎没有用新数据重新渲染模板。
这是因为,当您发送 POST 请求时,服务器的响应不会自动解释。您必须对服务器响应做一些事情,例如渲染它。
因此,您需要在 ajax 请求中添加一个成功参数:
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/upload/",
traditional: "true",
data: JSON.stringify({rows}),
dataType: "json",
success: function(response){
console.log(response)
document.open();
document.write(response);
document.close();
},
error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
});
由于您的服务器当前使用完全呈现的 html 页面进行响应,因此您可以覆盖示例中显示的页面的现有内容(尽管是不好的做法)。
最好创建一条新路由,专门用于验证表中的所有内容是否正确。您也可以考虑onChange()
在您的 html td 中使用来解决此问题,并编写一个 javascript 函数来检查输入现在是否有效,以防止整个 ajax 调用。
推荐阅读
- c# - 为什么即使 Directory.Exists 返回 true,它也会抛出 DirectoryNotFoundException?
- php - 在 Google App Engine (GAE) 上部署时无法识别 app.user
- json - 尝试将 JSON 结构上传到 Firebase 网络
- html - minmax() 忽略最小值并拉伸 div 以适应父高度
- ios - 在标签上添加 UITapGestureRcognizer 后 TTTAttributedLabel 链接不可点击
- java - 为 Eclipse 配置 jsr-305 注解
- python - 当确定条件失败时,是否有任何方法可以执行“无”?
- ios - 一天的谓词格式,用于搜索从 HealthKit 检索的 Steps Sample Array
- typo3 - 在TYPO3 Fluid中访问以“@”开头的数组变量?
- xslt - XSL 从节点获取下一个值