【发布时间】:2017-06-10 10:48:12
【问题描述】:
我正在尝试制作一个动态表单生成器。在构建过程之后,我试图通过脚本将所有表单数据放入 JsonObject 并将其传递给烧瓶视图,以便我可以将它们展示给用户。但我无法正确设置它。 这是调用javascript的按钮
<form action="/preview" method="post" role="form">
<button class="btn btn-primary" name = "submit" id = "submit">submit</button>
</form>
这是我进行 ajax 调用的脚本。
<script>
$(document).ready( function() {
$('#submit').click(function() {
var formdata = serialize();
$.ajax({
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(formdata),
dataType: 'json',
url: 'http://192.168.58.206:5000/index',
success: function (e) {
console.log(e);
},
error: function(error) {
console.log(error);
}
});
});
});
</script>
这是我尝试在烧瓶 python 中渲染的方法。
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
asd = request.json
session['formdata'] = asd
if 'formdata' in session:
return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
return render_template("index.html")
@app.route('/preview', methods=['GET', 'POST'])
def preview():
if 'formdata' in session:
renderedform = formbuilder(json.dumps(session['formdata']))
renderedform = renderedform.renderform()
session.pop('formdata')
return render_template("asd.html",renderform = renderedform)
return "Error"
我的 renderdorm() 方法将 json 对象作为参数,并为表单创建相应的 html 块。
但是当我以这种方式运行它时,有时按钮操作会在脚本运行并创建 json 对象之前将我定向到 /preview 路由。所以这会导致会话的表单数据为无。
任何想法如何传递该 json 对象以在预览中呈现?
【问题讨论】:
标签: javascript python html ajax flask