使用Bottle(Python)的AJAX提交表单
我在使用Bottle框架进行AJAX通信时遇到了一些问题。这是我第一次使用AJAX,所以很可能我只是基础知识掌握得不太对。希望有Bottle或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')
1 个回答
4
这里有几个问题。
- JavaScript是区分大小写的。XMLHTTPRequest 应该写成 XMLHttpRequest。你应该在JavaScript控制台看到过关于这个的错误信息。
- onReadyStateChange 应该是 onreadystatechange。
- 如果你解决了上面两个问题,你的AJAX调用会正常工作,但你只会得到“你没有输入任何内容。”的回应。这是因为你使用的是GET方法。你需要修改代码,让表单的值使用POST方法提交。
另外,为什么不使用jQuery来做AJAX呢?这样会让你的工作轻松很多。 :)