一、页面跳转
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()