【问题标题】:Using jQuery AJAX with Python's Bottle在 Python 的 Bottle 中使用 jQuery AJAX
【发布时间】:2012-10-17 09:38:47
【问题描述】:

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

这是我最初的尝试,但它不工作,我真的碰壁了(整天编程,我的大脑有点炸):

    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更改为输入的文本。

没有错误,当我按下按钮时它什么也没做。

有什么帮助吗?


已解决:表单按钮的类型必须是“提交”,而不是“按钮”。掌心。

【问题讨论】:

  • 错误是什么?在例如 Chrome 中打开开发者控制台以找到它
  • 哎呀,对不起。 Failed to load resource: Resource failed to load file:///F:/ajax

标签: jquery python ajax bottle


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    $("#ajaxP").load("/ajax", .../ajax 发送GET(不是POST)请求,并将#ajaxP 的内容替换为响应HTML。

    您可以通过在 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();
        });
    });​
    

    【讨论】:

    • 不,这并没有解决问题。仍然得到 404 资源没有加载错误。我将如何使用 POST 而不是 GET?
    • 我认为这将在 HTML/JS 方面起作用,但我仍然收到我认为是由 Bottle 引起的 Failed to load resource: Resource failed to load file:///F:/ajax 错误。
    • @Djentleman:我多次编辑了代码。您使用的 JS 代码是否与我的答案相符?
    • 确实如此。同样,我认为问题出在瓶子上。 AJAX 没有找到“/ajax”。
    • 你的 JS 错误信息很奇怪。您如何访问此网页?您在访问http://localhost:8080/form 吗?你不应该有file:/// URL。另外,打开debug mode
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多