一.通用方式
通用方式就是使用ajax或者$.post来提交。
前端html
1
2
3
4
5
6
7
8
9
10
11
|
< 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 >
|
将操作绑定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
$(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
}
|
1
2
3
4
5
6
7
|
@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:
1
2
3
4
5
6
7
8
9
10
11
|
< 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有很多内置的方式帮你校验你的提交,一个字:省事!
1
2
3
4
5
6
7
|
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()])
|
后端这时候就要变成:
1
2
3
4
5
6
|
@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)
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/alexkn/p/5027719.html