標籤:
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.ioloopimport 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頁面上。
使用Tornado實現Ajax請求