使用Bottle(Python)的AJAX提交表单

pat*_*ckn 6 python ajax bottle

我在使用Bottle框架进行AJAX通信时遇到了一些问题.这是我第一次使用AJAX,所以我可能只是错误的基础知识.希望瓶子/ AJAX大师可以指出这个新手正确的方向.这是我正在使用的代码:

#!/usr/bin/env python

from bottle import route, request, run, get


# Form constructor route

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

<html>
<head>
<script type="text/javascript">

    function loadXMLDoc()
    {
        xmlhttp = new XMLHTTPRequest();
        xmlhttp.onReadyStateChange = function()
        {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                document.getElementById("responseDiv").innerHTML = xmlhttp.responseText;
            }
        }

    xmlhttp.open("GET", "/ajax", true);
    xmlhttp.send();
    }   

</script>
</head>

<body>

    <form>
        <input name="username" type="text"/>
        <input type="button" value="Submit" onclick="loadXMLDoc()"/>
    </form>
    <div id="responseDiv">Change this text to what you type in the box above.</div>

</body>
</html> 

    '''

# Server response generator

@route('/ajax', method='GET')
def ajaxtest():
    inputname = request.forms.username
    if inputname:
        return 'You typed %s.' % (inputname)
    return "You didn't type anything."

run(host = 'localhost', port = '8080')
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 4

这里有几个问题。

  1. JavaScript 区分大小写。 XMLHTTPRequest应该是XMLHttpRequest。您应该已经在 J​​avascript 控制台中看到了有关此问题的错误。
  2. onReadyStateChange应该是onreadystatechange
  3. 如果您解决了上述两个问题,您的 AJAX 调用将可以工作,但您只会得到“您没有输入任何内容”。回复。这是因为您正在使用 GET。您需要更改代码,以便使用 POST 方法发布表单值。

另外,为什么不使用 jQuery 来执行 AJAX?这会让你的生活变得更加轻松。:)