【发布时间】:2011-07-15 08:10:45
【问题描述】:
我在 django 框架中对 ajax/jquery 帖子进行了简单的测试,但并不真正理解为什么输出没有进入模板页面。有人吗?
我可以在 firebug 的“响应”选项卡中看到帖子的内容,但是无论我尝试返回模板还是简单消息,浏览器本身都没有任何反应。相反,非 ajax 帖子按预期工作(加载新页面、发布消息)
我是 ajax/jquery/django 的新手,所以请原谅我的无知 :)
最终,我希望能够通过 jquery 将任意非表单变量传递给 django 视图。可能的?谢谢你:)
这是代码--
test.html:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
$(document).ready(function() {
$("#testForm").submit(function(event){
event.preventDefault();
$.ajax({
type:"POST",
url:"/test_results/"
});
});
return false;
});
</script>
</head>
<body>
<form id="testForm" action="/test_results/" method="post">
<input type="submit" id="go" name="go" value="Go!">
</form>
</body>
</html>
views.py:
from django.shortcuts import render_to_response
from django.http import HttpResponse
def test_ajax(request):
if request.is_ajax():
message = "Yes, AJAX!"
else:
message = "Not Ajax"
return HttpResponse(message)
#alternative test: return render_to_response('test_results.html')
urls.py:
(r'^test_results/$', views.test_ajax),
(r'^test/$', views.test),
还有几乎是空的 test_results.html:
<html>
<head>
</head>
<body>
test results
</body>
</html>
【问题讨论】:
-
请注意,您的
return false级别错误;它应该在$("#testForm").submit块内,即高一行,所以它在该块的关闭});之前。