【发布时间】:2010-03-09 19:19:39
【问题描述】:
我正在尝试了解 Django + Jquery 和 Ajax 调用如何协同工作。
它只是一个简单的 /test/ url,显示单个输入表单,提交后通过 ajax 从服务器检索答案。
为此我写了一个非常小的视图:
def test(request):
if request.is_ajax():
from django.http import HttpResponse
post_text = request.POST.get("post_data")
return HttpResponse("{'response_text': '"+post_text+" recieved.'}", mimetype="application/json")
else:
return render_to_response('test.html', {},context_instance =RequestContext(request))
我已经在 urls.py 中将这个 url 规则写入了我的 urlpattern:
(r'^test/$', 'myapp.views.test'),
这是我的 test.html 模板:
<html>
<head><title>template</title></head>
<script type="text/javascript" src="/media/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#post_form').submit(function(event){
event.preventDefault(); // cancel the default action
var form = this;
var data = {}
data.post_data = $(form).find('input[@name=our_text]').val();
$.post("/test/",
data,
function(responseData) {
alert(responseData.response_text);
},
"json"
);
});
});
</script>
<body>
<form id="post_form" method="post">
INPUT: <input type="text" name="our_text" />
<input type="submit" value="Add" />
</form>
</body>
</html>
一旦我填写输入字段并提交,它似乎没有在我的 www.mysite.com/test/ 上做任何回复。可能是什么问题?
【问题讨论】:
-
你的视图被调用了吗?您的 POST 数据是否符合您的预期?另外,我建议使用 json 模块来处理对 json 的编码。
-
Firebug 是否显示任何类型的错误?