【发布时间】:2013-05-24 17:52:55
【问题描述】:
基本上我需要在 django 中完成类似于 http://www.w3schools.com/jquery/jquery_ajax_get_post.asp 的东西。我已经下载了示例并使用 localhost + php 在本地对其进行了测试,并且效果很好,但是无论示例多么简单,我似乎都无法让它在 django 中工作。这基本上是我根据上面链接中的示例所做的,稍作修改
javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#my_form").submit(function(){
$.post("",
{name:"Donald Duck",
city:"Duckburg"},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
})
.fail(function() { alert("error"); });
return false;
});
});
</script>
网址:
url(r'^ajax/$', views.ajax_test, name="ajax"),
意见:
def ajax_test(request):
if request.method == 'POST' and request.is_ajax():
name = request.POST['name']
city = request.POST['city']
message = name + ' lives in ' + city
return HttpResponse(json.dumps({'message': message})) #tried without the json. Doesn't work either
return render(request, 'books/ajaxTest.html')
html:
<form id="my_form" action="" method="post" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>{% csrf_token %}
<input type="submit" value="Send">
</form>
该表单应该包含一个 django 表单,但由于我什至无法获得基本的工作,那将是毫无意义的。有人提到了 csrf_token 标签,但删除它也不能解决问题。上面示例的输出基本上只产生 alert('error') 而没有别的。我已经经历了很多例子,但我什至无法让最基本的例子起作用
【问题讨论】:
-
如果您在 Chrome Inspector 或 Firefox Firebug 中检查您的 Ajax 响应,您应该会看到一些错误消息,这些消息会引导您了解如何修复它。
-
我写了一篇使用JQuery在Django中实现Ajax的教程:aliteralmind.wordpress.com/2014/09/21/jquery_django_tutorial