3

Python の Bottle モジュールで jQuery AJAX を使用する方法を理解しようとしています。

これが私の最初の試みですが、うまくいかず、本当に壁にぶつかっています(一日中プログラミングをしていて、私の脳は少し揚げられています):

    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')

基本的にできるようにしたいのは、テキストボックスにテキストを入力してボタンをクリックし、「ajaxP」のinnerHTMLを入力したテキストに変更することです。

エラーはありません。ボタンを押しても何もしません。

何か助けはありますか?


解決済み: フォーム ボタンは、「ボタン」ではなく「送信」タイプである必要があります。フェイスパーム。

4

2 に答える 2

2

$("#ajaxP").load("/ajax", ...GET( ではないPOST) リクエストを に送信し、 のコンテンツをレスポンス HTML/ajaxに置き換えます。#ajaxP

Python コードを に変更することmethod='POST'で問題を解決できます。method='GET'

または、フォームの送信を防ぎ、代わりに 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();
    });
});​
于 2012-10-27T08:31:07.243 に答える
0

フォーム ボタンのタイプを ではtype= "submit"なくに変更してください"button"

于 2017-11-01T13:19:18.147 に答える