使用Tornado实现Ajax请求
Ajax,指的是網(wǎng)頁(yè)異步刷新,一般的實(shí)現(xiàn)均為js代碼向server發(fā)POST請(qǐng)求,然后將收到的結(jié)果返回在頁(yè)面上。
?
這里我編寫(xiě)一個(gè)簡(jiǎn)單的頁(yè)面,ajax.html
<html> <head><title>測(cè)試Ajax</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <style type="text/css"> #result{border: 10px;font-size: 50px;background: #ff0fef; }</style> </head> <body><input type="text" id="word" > <br><button id="foo">點(diǎn)擊</button><div id="result"></div><script type="text/javascript">$("#foo").click(function(){var word = $("#word").val(); //獲取文本框的輸入//把word發(fā)給后臺(tái)php程序//返回的數(shù)據(jù)放在data中,返回狀態(tài)放在status $.post("/test",{message:word}, function(data,status){if(status == "success"){$("#result").html(data);}else{alert("Ajax 失敗");}});});</script></body> </html>注意,從上面的代碼可以看出,數(shù)據(jù)存儲(chǔ)在“message”字段中。
所以后臺(tái)從message中解析數(shù)據(jù),我們記得是get_argument方法。
所以后臺(tái)的python代碼為:
import tornado.ioloop import tornado.webclass MainHandler(tornado.web.RequestHandler):def get(self):self.render("ajax.html")class AjaxHandler(tornado.web.RequestHandler):def post(self):#self.write("hello world")self.write(self.get_argument("message"))application = tornado.web.Application([(r"/", MainHandler),(r"/test", AjaxHandler),])if __name__ == '__main__':application.listen(8888)tornado.ioloop.IOLoop.instance().start() 訪問(wèn)首頁(yè),就渲染ajax前端頁(yè)面,而AjaxHandler處理真正的ajax異步請(qǐng)求。?
這里總結(jié)下流程:
1.用戶訪問(wèn)home頁(yè)面,tornado使用MainHandler返回其中的ajax.html頁(yè)面
2.用戶填寫(xiě)信息,點(diǎn)擊按鈕,因?yàn)橹凹虞djs代碼,注冊(cè)了回調(diào)函數(shù),所以觸發(fā)Ajax
3.js向后臺(tái)發(fā)post請(qǐng)求。
4.根據(jù)請(qǐng)求的URL,tornado使用AjaxHandler處理post請(qǐng)求,將信息原樣返回。
5.js收到數(shù)據(jù),調(diào)用之前的回調(diào)函數(shù),將結(jié)果顯示在html頁(yè)面上。
轉(zhuǎn)載于:https://www.cnblogs.com/inevermore/p/4192615.html
總結(jié)
以上是生活随笔為你收集整理的使用Tornado实现Ajax请求的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【转】15个最受欢迎的Python开源框
- 下一篇: 颜色表