原生态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>
原文地址:https://www.cnblogs.com/wenxianfeng/p/10366639.html
时间: 2024-10-13 02:44:25