Search code examples
javascripthtmlwebtornado

(tornado)how can I pass argument to server when a button is pressed?


I'm new to python tornado.I'm now building a web site When I want to send an argument to server by pressing a button,I don't know how to catch it on tornado. How do I know which button was pressed ?


Solution

  • a simple ajax GET request with jquery can do the job :

    class Application(tornado.web.Application):
        """Tornado web class. Create all the routes used by tornado_start"""
    
        def __init__(self):
            handlers = [
                (r"/", Index),
                (r"/explicit_action_url/", ActionHandler)
            ]
    ...
    
    class ActionHandler(tornado.web.RequestHandler):
        def get(self):
            print("button click")
    
    
    class Index(tornado.web.RequestHandler):
        def get(self):
            self.render("index.html")
    

    and in your index.html

    <button id="btn" type="button">click me</button>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>
        $("#btn").click(function () {
            $.ajax({
                type: 'GET',
                url: "/explicit_action_url/",
                success: function (data) {
                    alert("success")
                }
            });
        });
    </script>