【发布时间】:2018-04-03 08:45:27
【问题描述】:
我想运行一个烧瓶应用程序,用户可以在其中提供一些用户输入,这些输入用于创建一个 HTML 页面,然后应该在新选项卡中显示该页面。 HTML 是使用外部工具创建的(这里由函数 get_html 模仿,它实际上将用户输入作为参数),所以我不能只使用我呈现的模板(我认为)。
我已经可以接受用户输入并创建我希望显示的 HTML,但是,我还没有设法为它打开一个新选项卡。如何实现?
这是我的代码:
from __future__ import print_function, division
from flask import Flask, render_template, request, jsonify
import json
# Initialize the Flask application
app = Flask(__name__)
@app.route('/html_in_tab')
def get_html():
# provided by an external tool
# takes the user input as argument (below mimicked by a simple string concatenation)
return '<!DOCTYPE html><title>External html</title><div>Externally created</div>'
@app.route('/_process_data')
def data_collection_and_processing():
# here we collect some data and then create the html that should be displayed in the new tab
some_data = json.loads(request.args.get('some_data'))
# just to see whether data is retrieved
print(some_data)
# oversimplified version of what actually happens; get_html comes from an external tool
my_new_html = get_html() + '<br>' + some_data
print(my_new_html)
# this html should now be displyed in a new tab
return my_new_html
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
index.html 如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Get new tab!</h3>
</div>
<button type="button" id="process_input">Process!</button>
<a href="/html_in_tab" class="button" target='_blank'>Go to results</a>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
// clicking the button works fine: data is processed correctly
$('#process_input').bind('click', function() {
$.getJSON('/_process_data', {
some_data: JSON.stringify('some data')
});
// can this be changed to show the processed html?
window.open("/html_in_tab", "_blank");
return false;
});
});
</script>
</body>
</html>
所以,现在window.open 部分打开了一个新选项卡,但它应该显示my_new_html,即data_collection_and_processing 新创建的HTML。我怎样才能做到这一点?
【问题讨论】: