How to use Flask's render
I am hoping to get an answer to this similar question:
I have a jQuery form that sends JSON data to a certain URL that is served by Flask:
<div id="form">
<form id="send">
<input type="submit" value="Continue" >
</form>
</div>
jQuery(document).on('ready', function() {
jQuery('form#send').bind('submit', function(event){
event.preventDefault();
var form = this;
json = geojson.write(vectors.features);
$.ajax({
type: "POST",
contentType: 'application/json',
url: $SCRIPT_ROOT + "/create",
dataType: "json",
success: function(){},
data: json
});
});
});
On the Flask side, I have a simple function that renders an HTML page displaying the JSON object:
@app.route('/create', methods=['POST'])
def create():
content = request.json
print content
return render_template('string.html', string = content)
I know the JSON is being passed, because I can see it printed in the console running the Flask server:
The problem is that the template is rendered as part of the response of the Ajax request, but I want the template to be rendered as a new html page:
尝试这个,
$.ajax({
type: "POST",
contentType: 'application/json',
url: $SCRIPT_ROOT + "/create",
dataType: "json",
success: function(){},
data: json
success:function(response){
document.write(response);
}
});
So it turns out I actually didn't need to use jQuery for this, instead I can submit JSON simply using an html form with a hidden field (as hinted at in this question):
<div id="form">
<form id="send" method="post" action="create" onsubmit="getJSON()" enctype='application/json'>
<input type="submit" value="Continue" />
<input type="hidden" name="jsonval" value=""/>
</form>
</div>
And then use javascript to populate the form when the button is clicked:
function getJSON(){
json = geojson.write(vectors.features);
var formInfo = document.forms['send'];
formInfo.jsonval.value = json;
}
链接地址: http://www.djcxy.com/p/71894.html
上一篇: 模板在Heroku上不起作用
下一篇: 如何使用Flask的渲染