一、頁面跳轉
html頁面跳轉,可以使用form表單或者a標簽,如下:
(一)通過form表單的action設置:跳轉同時可提交數據
(二)通過a標簽href超鏈接:只跳轉不提交數據
二、提交數據
html頁面的數據提交至后台,可以使用form表單或者Ajax,如下:
(一)使用form表單提交數據:頁面刷新、跳轉
可提交文本、文件、選項等多種類型的數據,並在后台應用對應的語句提取,詳情見代碼,
start.py:

#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web allData = [] # 全體數據庫 # 個體數據 class IndexHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') def post(self, *args, **kwargs): self.write("it is post") class LoginHandler(tornado.web.RequestHandler): def get(self): self.render('login.html',allData = allData) def post(self, *args, **kwargs): infoDict = {} # 單一值獲取 userName = self.get_argument('name') # 內部調用的self.request()模塊 password = self.get_argument('pwd') E_mail = self.get_argument('email') infoDict['userName'] = userName infoDict['password'] = password infoDict['E_mail'] = E_mail # 單選值獲取 sex_number = self.get_argument('sex') if sex_number == '1': sex = 'female' else: sex = 'male' infoDict['sex'] = sex # 多選擇獲取 hobieList_number = self.get_arguments('hobie') hobieList = [] for i in hobieList_number: if i == '1': hobieList.append('游泳') elif i == '2': hobieList.append('跑步') elif i == '3': hobieList.append('輪滑') elif i == '4': hobieList.append('跳高') elif i == '5': hobieList.append('散步') elif i == '6': hobieList.append('跳舞') else: hobieList.append('其他') infoDict['hobie'] = hobieList # 多文本獲取 otherHobie = self.get_argument('otherHobie') infoDict['otherHobie'] = otherHobie # # 上傳文件獲取(錯誤方法) # myPhoto = self.get_argument('myFile') # 這樣只能獲取文件名 # print(myFile) # 上傳文件獲取(正確方法) file_metas = self.request.files['myFile'] # request模塊,包含所有請求相關方法和信息 for meta in file_metas: # file_metas中只有一個元素,但tornado規定這里必須迭代 fileName = meta['filename'] infoDict['myPhoto'] = fileName import os with open(os.path.join('statics','img',fileName),'wb') as upFile: # 指定存儲路徑 upFile.write(meta['body']) # 瀏覽器輸出 # import json # self.write(json.dumps(infoDict)) allData.append(infoDict) self.redirect("/login") # 路徑解析 settings = { "template_path":"views", "static_path":"statics", "static_url_prefix":"/sss/", "xsrf_cookies":True, } # 二級路由,先匹配域名, application = tornado.web.Application([ (r"/index",IndexHandler), (r"/login",LoginHandler), ],**settings) # 開啟服務器,監聽 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
login.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <p>現有信息如下:</p> <ul style="list-style-type:none;"> {% for item in allData %} <li> <img style="height:50px;width:50px;" src="/sss/img/{{item['myPhoto']}}"> <span>{{item['userName']}}+{{item['E_mail']}}+{{item['sex']}}+{{item['hobie']}}+{{item['otherHobie']}}</span> </li> {% end %} </ul> <hr> <p>新增信息如下:</p> <form action="/login" method="post" enctype="multipart/form-data"> <!--上傳文件添加enctype--> {% raw xsrf_form_html() %} <!--單一值--> <input type="text" name="name" placeholder="user" /> <input type="text" name="email" placeholder="email" /> <input type="password" name="pwd" placeholder="password" /> <!--單選--> <p> <span>Are you a girl ?</span>   <span>yes</span><input type="radio" name="sex" value="1" />   <span>no</span><input type="radio" name="sex" value="2" /> </p> <!--多選--> <p> <span>What do you like?</span><br> <label for="swim">游泳</label><input type="checkbox" name="hobie" value="1" id="swim" />   <label for="run">跑步</label><input type="checkbox" name="hobie" value="2" id="run" />   <label for="skate">輪滑</label><input type="checkbox" name="hobie" value="3" id="skate" />   <label for="jump">跳高</label><input type="checkbox" name="hobie" value="4" id="jump" />   <label for="walk">散步</label><input type="checkbox" name="hobie" value="5" id="walk" />   <label for="dance">跳舞</label><input type="checkbox" name="hobie" value="6" id="dance" />   <label for="else">其他</label><input type="checkbox" name="hobie" value="7" id="else" /> </p> <!--多文本--> <textarea name="otherHobie" style="height:50px;width:500px;" placeholder="請輸入其他愛好..."></textarea><br> <!--上傳文件--> <input type="file" name="myFile" /><br> <!--確定表單--> <input type="submit" />  <input type="reset"/> </form> </body> </html>
(二)使用Ajax提交數據:頁面不刷新、不跳轉
提交文本:

<script> function SubmitFunc(){ <!--# 方式一:.post--> <!--$.post(--> <!--'/login',--> <!--{'username':$("#userName").val(),'password':$("#passWord").val()},--> <!--function(severResponse){console.log(severResponse);},--> <!--);--> <!--# 方式二:.ajax--> $.ajax({ method:'POST', url:'/login', async:true, data:{'username':$("#userName").val(),'password':$("#passWord").val()}, dataType:'json', <!--指定返回數據類型,進行相應的解析--> success:function(severResponse){console.log(severResponse);}, error:function(){alert(arguments[1]);}, }); }; </script>
上傳文件:formData對象受瀏覽器限制

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <!--利用Ajax上傳圖片--> <input type="file" id="myPic" /> <input type="button" value="上傳(原生)" onclick="upLoadPicOriginal()" /> <br> <input type="file" id="img" /> <input type="button" value="上傳(jQuery)" onclick="upLoadPicJQuery()" /> <!--1、原生方式--> <script> function upLoadPicOriginal(){ var picObj = document.getElementById("myPic").files[0]; <!--獲取文件對象--> var form = new FormData(); <!--創建Form對象--> form.append("myFile",picObj); <!--文件對象加入Form--> var xhr = new XMLHttpRequest(); <!--創建Ajax上傳--> xhr.open("post","/login",true); xhr.send(form); }; </script> <!--2、jQuery方式--> <script src="sss/js/jquery-1.12.4.min.js"></script> <script> function upLoadPicJQuery(){ var fileObj = $("#img")[0].files[0]; var form = new FormData(); form.append('myFile',fileObj); $.ajax({ type:"POST", url:"/login", data:form, processData:false, <!--tell jquery no to process the data--> contentType:false, <!--tell jquery no to set the contentType--> success:function(arg){console.log(arg)}, }); } </script> </body> </html>
(三)使用iframe提交數據:不受瀏覽器限制、頁面不刷新
利用iframe加載時不刷新、兼容性好的特性,將form表單提交之后的返回信息,設置在指定的、隱藏的iframe中呈現,
login.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> <style> .hide{ display:none; } </style> </head> <body> <!--iframe標簽加載時不刷新,實現文件上傳不受兼容性影響,推薦--> <form name="form" id="my_form" action="/login" method="post" enctype="multipart/form-data"> <div id="main"> <input type="text" name="user" placeholder="name" /> <input type="email" name="E_mail" placeholder="email" /> <input name="myFile" id="my_file" type="file" /> <input name="action" value="Upload" type="button" onclick="redirect()" /> <iframe name="myIframe" id="my_iframe" src="" class="hide"></iframe> </div> </form> <script src="sss/js/jquery-1.12.4.min.js"></script> <script> function redirect(){ document.getElementById('my_iframe').onload = Testt; <!--iframe加載完,執行函數Testt--> document.getElementById('my_form').target = 'myIframe'; <!--提交form表單后的返回內容呈現在iframe中--> document.getElementById('my_form').submit(); } function Testt(ths){ var t = $("#my_iframe").contents().find("body").text(); <!--iframe提交請求后從服務器獲得的內容--> console.log(t); } </script> </body> </html>
start.py:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web
class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.render('login.html')
def post(self, *args, **kwargs):
userName = self.get_argument('user')
email = self.get_argument('E_mail')
file_metas = self.request.files['myFile']
for meta in file_metas:
fileName = meta['filename']
import os
with open(os.path.join('statics','img',fileName),'wb') as upFile: # 指定存儲路徑
upFile.write(meta['body'])
self.write("hihihihihi___"+userName+"___"+email)
# 路徑解析
settings = {
"template_path":"views",
"static_path":"statics",
"static_url_prefix":"/sss/",
}
# 二級路由,先匹配域名,
application = tornado.web.Application([
(r"/login",LoginHandler),
],**settings)
# 開啟服務器,監聽
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()