flask表单提交的两种方式
一.通用方式
通用方式就是使用ajax或者$.post来提交。
前端html
<form method="post" action="/mockservice" method = "post"> ... <div class="form-group"> <label>data <font style="color:#a94442" size="2"> <input class="form-control" id="data" name="data"> </div> <div class="form-group"> <button id="start" type="submit" class="btn btn-default">Submit  </button> </div> </form>
将操作绑定
$(document).ready(function() { MockTask.start(); }); MockTask ={ startId: "start_mock", start: function(){ $('#'+this.startId).click(function (){ ...var data = $('#data').val(); var form_data = JSON.stringify({ ..."data": data }); MockSubmit.createTask(form_data); }); }, }; MockSubmit = { createTask: function(data){ var url = "/mockservice"; $.post(url,data,function(result){ if (result.code != 'SUCC'){ alert("failed to create a new api.") } else { alert("succ"); } }); } }; function isEmptyString(info) { if (info == null || info == undefined || info.length == 0){ return true; } return false }
这样通过js来实现提交表单的功能,然后flask后端
@app.route("/mockservice",methods=['GET','POST']) def MockController(): form = MockCreate() if request.method == 'POST': code = request.form['code'] api = request.form['api'] return ...
通用方式的好处就是在其他框架中也适用。而且也并不复杂。
二.比较正宗的flask方式
前端html:
<form method="post" action="/mockservice" method = "post"> ... <div class="form-group"> <label>data <font style="color:#a94442" size="2"> <input class="form-control" id="data" name="data"> </div> <div class="form-group"> <button type="submit" class="btn btn-default">Submit  </button> </div> </form>
前端这时候可以不用绑定操作了,但需要新建一个form对象,用这种方式的好处就是flask有很多内置的方式帮你校验你的提交,一个字:省事!
class MockCreate(Form): user_email = StringField("email address",[validators.Email()]) api = StringField("api",[Required()]) submit = SubmitField("Submit") code = IntegerField("code example: 200",[Required()]) alias = StringField("alias for api") data = TextAreaField("json format",[Required()])
后端这时候就要变成:
@app.route("/mockservice",methods=['GET','POST']) def MockController(): form = MockCreate() code = form['code'] api = form['api'] return render_template("testf.html",api=api,data=code)