原生態Ajax提交表單:需要藉助XMLHttpRequest對象的open,要收通過post發送請求還要setRequsetHeader,然後把數據發送給後端,代碼如下 目錄結構 index.py代碼 1 #index.py 2 #!/usr/bin/env python 3 #-*- coding ...
原生態Ajax提交表單:需要藉助XMLHttpRequest對象的open,要收通過post發送請求還要setRequsetHeader,然後把數據發送給後端,代碼如下
目錄結構
index.py代碼
1 #index.py 2 #!/usr/bin/env python 3 #-*- coding:utf-8 -*- 4 import tornado.web 5 import tornado.ioloop 6 class indexHandler(tornado.web.RequestHandler): 7 def get(self, *args, **kwargs): 8 # ff = self.get_argument('user',None) 9 # print(ff) 10 self.render('login.html') 11 def post(self, *args, **kwargs): 12 dic = {'status': True,'message':''} 13 if (self.get_argument('username') == 'alex' and 14 self.get_argument('password') == '123'): 15 pass 16 else: 17 dic['status'] = False 18 dic['message'] = '賬號或密碼不對' 19 import json 20 self.write(json.dumps(dic)) 21 22 settings ={'template_path':'view', 23 'static_path':'static' 24 } 25 app = tornado.web.Application([(r"/login",indexHandler) 26 ],**settings) 27 if __name__ == "__main__": 28 app.listen('8000') 29 tornado.ioloop.IOLoop.instance().start()View Code
login.html代碼
1 <!--login.html--> 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>Title</title> 7 </head> 8 <body> 9 10 <input id="user" type="text" name="username"> 11 <input id="pwd" type="password" name="password"> 12 <!--<input type="checkbox">7天免登陸--> 13 <input type="button" value="登陸" onclick="SubmitForm();"> 14 15 <script src="static/jquery-1.8.2.js"></script> 16 <script> 17 // xhr = null; 18 // function SubmitForm() { 19 // xhr = new XMLHttpRequest(); 20 // xhr.open('POST','/login',true); 21 // xhr.onreadystatechange = func; 22 // xhr.setRequestHeader("CONTENT-TYPE", "application/x-www-form-urlencoded;") 23 // xhr.send("username="+document.getElementById('user').value+";password="+document.getElementById('pwd').value) 24 // } 25 // function func() { 26 // if (xhr.readyState == 4){ 27 // console.log(xhr.responseText); 28 // ret = JSON.parse(xhr.responseText) 29 // alert(ret) 30 // alert(ret.status) 31 // alert(ret.message) 32 // } 33 // } 34 35 $.post('/login',{'username':'alex','password':'1233'},function (callback) { 36 alert(callback) 37 }) 38 </script> 39 </body> 40 </html>View Code