向后台提交数据:通过form表单提交数据需刷新网页 但通过Ajax提交数据不用刷新网页可通过原生态Ajax或jqueryAjax。Ajax代码部分

时间:2023-03-09 01:47:03
向后台提交数据:通过form表单提交数据需刷新网页 但通过Ajax提交数据不用刷新网页可通过原生态Ajax或jqueryAjax。Ajax代码部分

原生态Ajax提交表单:需要借助XMLHttpRequest对象的open,要收通过post发送请求还要setRequsetHeader,然后把数据发送给后端,代码如下

目录结构

向后台提交数据:通过form表单提交数据需刷新网页 但通过Ajax提交数据不用刷新网页可通过原生态Ajax或jqueryAjax。Ajax代码部分

index.py代码

 #index.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import tornado.web
import tornado.ioloop
class indexHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
# ff = self.get_argument('user',None)
# print(ff)
self.render('login.html')
def post(self, *args, **kwargs):
dic = {'status': True,'message':''}
if (self.get_argument('username') == 'alex' and
self.get_argument('password') == ''):
pass
else:
dic['status'] = False
dic['message'] = '账号或密码不对'
import json
self.write(json.dumps(dic)) settings ={'template_path':'view',
'static_path':'static'
}
app = tornado.web.Application([(r"/login",indexHandler)
],**settings)
if __name__ == "__main__":
app.listen('')
tornado.ioloop.IOLoop.instance().start()

login.html代码

 <!--login.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <input id="user" type="text" name="username">
<input id="pwd" type="password" name="password">
<!--<input type="checkbox">7天免登陆-->
<input type="button" value="登陆" onclick="SubmitForm();"> <script src="static/jquery-1.8.2.js"></script>
<script>
// xhr = null;
// function SubmitForm() {
// xhr = new XMLHttpRequest();
// xhr.open('POST','/login',true);
// xhr.onreadystatechange = func;
// xhr.setRequestHeader("CONTENT-TYPE", "application/x-www-form-urlencoded;")
// xhr.send("username="+document.getElementById('user').value+";password="+document.getElementById('pwd').value)
// }
// function func() {
// if (xhr.readyState == 4){
// console.log(xhr.responseText);
// ret = JSON.parse(xhr.responseText)
// alert(ret)
// alert(ret.status)
// alert(ret.message)
// }
// } $.post('/login',{'username':'alex','password':'1233'},function (callback) {
alert(callback)
})
</script>
</body>
</html>