简体   繁体   English

使用jQuery AJAX和Python的瓶子

[英]Using jQuery AJAX with Python's Bottle

I'm trying to figure out how to use jQuery AJAX with Python's Bottle module. 我正在试图弄清楚如何在Python的Bottle模块中使用jQuery AJAX。

Here is my initial attempt but it isn't working and I'm really hitting a wall (been programming all day and my brain is a bit fried): 这是我最初的尝试,但它不起作用,我真的撞墙了(整天编程,我的大脑有点油炸):

    from bottle import route, request, run, get

@route('/form')
def construct_form():
    return '''

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('form').submit(function(e) {
                $.ajax({
                    type: 'POST',
                    url: '/ajax',
                    data: $(this).serialize(),
                    success: function(response) {
                        $('#ajaxP').html(response);
                    }
                });
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form method="POST" action="/ajax">
        <input id="ajaxTextbox" name="text" type"text" />
        <input id="ajaxButton" type="button" value="Submit" />
    </form>
    <p id="ajaxP">Nothing to see here.</p>
</body>
</html>

    '''

@route('/ajax', method='POST')
def ajaxtest():
    theText = request.forms.text
    if theText:
        return theText
    return "You didn't type anything."

run(host = 'localhost', port = '8080')

Basically, what I want to be able to do is enter text into the textbox, click the button, and have the innerHTML of "ajaxP" change to the entered text. 基本上,我希望能够做的是在文本框中输入文本,单击按钮,并将innerHTML“ajaxP”更改为输入的文本。

No errors, it just doesn't do anything when I push the button. 没有错误,当我按下按钮时它没有做任何事情。

Any help? 有帮助吗?


SOLVED : The form button needs to be of type "submit", not "button". 已解决 :表单按钮需要是“提交”类型,而不是“按钮”。 Facepalm. 捂脸。

$("#ajaxP").load("/ajax", ... sends a GET (not a POST ) request to /ajax and replaces the content of #ajaxP with the response HTML. $("#ajaxP").load("/ajax", ...发送GET (而不是POST )请求/ajax和替换的内容#ajaxP与响应的HTML。

You can fix your problem by changing method='POST' to method='GET' in your Python code. 您可以通过在Python代码中将method='POST'更改为method='GET'来解决您的问题。

Or you can fix your JS by preventing the form submit and sending an AJAX request instead: 或者您可以通过阻止表单提交并发送AJAX请求来修复您的JS:

$(document).ready(function() {
    $('form').submit(function(e) {
        $.ajax({
            type: 'POST',
            url: '/ajax',
            data: $(this).serialize(),
            success: function(response) {
                $('#ajaxP').html(response);
            }
        });

        e.preventDefault();
    });
});​

请修改表单按钮的type= "submit"type= "submit"而不是"button"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM