2

I'm trying to figure out how to use jQuery AJAX with Python's Bottle module.

I've created a very basic page containing two buttons, one controlled by jQuery and the other one inside a form as a submit button. Both buttons just send a POST request to the a bottle server which should respond with a "Done!" message.

This is the code of the template:

<!DOCTYPE html>
<html>
    <head>
        <title>Test Template</title>
        <!-- JQuery JS -->
        <script src="http://code.jquery.com/jquery.js"></script>

        <script>
            $(document).ready(function() {
                $('button').on('click', function(){
                    $.post("/home");
                });
            });
        </script>

    </head>
    <body>
        <button>Submit</button>
        <form action="/home" method="post" enctype="multipart/form-data">
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

And this is the code of the bottle server:

from bottle import route, run, template

@route('/home')
def home():
    return template('template')

@route('/home', method='POST')
def homePost():
    return  "Done!"

run(host='localhost', port=8080, debug=True)
run(reloader=True)

Why clicking the form button returns the message correctly but clicking on the jQuery one does nothing? Is jQuery blocking bottle's response somehow?

Thanks for your help.

Pablo

4

1 回答 1

3

...because the jquery button sends an ajax request to the server. An ajax request happens behind the scenes and does nothing to the page. On the other hand, when you click on a form's submit button a new page is loaded containing whatever the server sent back.

You need to specify a function in your jquery ajax request that will be called when the server returns the data. Inside the function, you can do something with the data--typically inserting it into an already existing tag, e.g.

$.post("/home", function(dataFromServer) {
  $('#mydiv').html(dataFromServer);
}

The beauty of an ajax request is that you can retrieve data from the server and then insert it into a page--all without reloading a page.

于 2013-07-01T06:52:40.230 回答