【问题标题】:jQuery and form POST difference to python BottlejQuery 和表单 POST 与 python Bottle 的区别
【发布时间】:2013-07-01 06:38:58
【问题描述】:

我正在尝试弄清楚如何将 jQuery AJAX 与 Python 的 Bottle 模块一起使用。

我创建了一个非常基本的页面,其中包含两个按钮,一个由 jQuery 控制,另一个在表单中作为提交按钮。这两个按钮只是向瓶子服务器发送一个 POST 请求,该服务器应该以“完成!”作为响应。消息。

这是模板的代码:

<!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>

这是瓶子服务器的代码:

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)

为什么单击表单按钮会正确返回消息,但单击 jQuery 按钮却什么也没做? jQuery 是否以某种方式阻止了瓶子的响应?

感谢您的帮助。

巴勃罗

【问题讨论】:

    标签: jquery python http-post bottle


    【解决方案1】:

    ...因为 jquery 按钮向服务器发送 ajax 请求。 ajax 请求发生在幕后,对页面没有任何作用。另一方面,当您单击表单的提交按钮时,会加载一个新页面,其中包含服务器发回的任何内容。

    您需要在您的 jquery ajax 请求中指定一个函数,该函数将在服务器返回数据时被调用。在函数内部,您可以对数据做一些事情——通常将其插入到已经存在的标签中,例如

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

    ajax 请求的美妙之处在于您可以从服务器检索数据,然后将其插入到页面中——所有这些都无需重新加载页面。

    【讨论】:

      猜你喜欢
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 2013-06-04
      相关资源
      最近更新 更多