使用Tornado实现Ajax请求
生活随笔
收集整理的這篇文章主要介紹了
使用Tornado实现Ajax请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Ajax,指的是網頁異步刷新,一般的實現均為js代碼向server發POST請求,然后將收到的結果返回在頁面上。
?
這里我編寫一個簡單的頁面,ajax.html
<html> <head><title>測試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">點擊</button><div id="result"></div><script type="text/javascript">$("#foo").click(function(){var word = $("#word").val(); //獲取文本框的輸入//把word發給后臺php程序//返回的數據放在data中,返回狀態放在status $.post("/test",{message:word}, function(data,status){if(status == "success"){$("#result").html(data);}else{alert("Ajax 失敗");}});});</script></body> </html>注意,從上面的代碼可以看出,數據存儲在“message”字段中。
所以后臺從message中解析數據,我們記得是get_argument方法。
所以后臺的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() 訪問首頁,就渲染ajax前端頁面,而AjaxHandler處理真正的ajax異步請求。?
這里總結下流程:
1.用戶訪問home頁面,tornado使用MainHandler返回其中的ajax.html頁面
2.用戶填寫信息,點擊按鈕,因為之前加載js代碼,注冊了回調函數,所以觸發Ajax
3.js向后臺發post請求。
4.根據請求的URL,tornado使用AjaxHandler處理post請求,將信息原樣返回。
5.js收到數據,調用之前的回調函數,將結果顯示在html頁面上。
轉載于:https://www.cnblogs.com/inevermore/p/4192615.html
總結
以上是生活随笔為你收集整理的使用Tornado实现Ajax请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】15个最受欢迎的Python开源框
- 下一篇: 颜色表