向后台提交数据:通过form表单提交数据需刷新网页 但通过Ajax提交数据不用刷新网页可通过原生态Ajax或jqueryAjax。Ajax代码部分
程序员文章站
2022-06-07 18:55:16
原生态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()
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>