How To Create Html Using User Input And Display It In A New Tab?
I would like to run a flask application where the user can provide some user input which is used to create a HTML page which should then be displayed in a new tab. The HTML is crea
Solution 1:
At the moment you're just opening a new window at the endpoint "/html_in_tab"
which will hit the Flask route for get_html()
and show the standard HTML with no user input.
One method you could try is to open a new window and set the document body innerHTML with the updated content:
<scripttype="text/javascript">
$(document).ready(function() {
$('#process_input').bind('click', function() {
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
})
returnfalse;
});
});
</script>
Solution 2:
Change your html as shown below:
<!DOCTYPE html><htmllang="en"><head><linkhref="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"rel="stylesheet"></head><body><divclass="container"><divclass="header"><h3class="text-muted">Get new tab!</h3></div><buttontype="button"id="process_input">Process!</button><ahref="/html_in_tab"class="button"target='_blank'>Go to results</a></div><scriptsrc="https://code.jquery.com/jquery-1.12.4.js"type="text/javascript"></script><scripttype="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("/process_data", "_blank");
returnfalse;
});
});
</script></body></html>
and Python script as shown below:
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')defget_html():
# provided by an external toolreturn'<!DOCTYPE html><title>External html</title><div>Externally created</div>'@app.route('/_process_data')defdata_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 retrievedprint(some_data)
# oversimplified version of what actually happens; get_html comes from an external tool
my_new_html = get_html() + '<br>' + some_data
withopen('templates/changed_html.html','w') as f: #write the html string to file
f.writelines(my_new_html)
# this html should now be displyed in a new tabreturn''@app.route('/process_data')defprocess_data():
return render_template('changed_html.html')
@app.route('/')defindex():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Post a Comment for "How To Create Html Using User Input And Display It In A New Tab?"