使用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.web

class 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頁面上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM