需要一个简单的django表单的工作ajax示例

基本上我需要类似于在django中完成的http://www.w3schools.com/jquery/jquery_ajax_get_post.asp 。 我已经下载了样本并使用localhost + php在本地进行了测试,但它运行良好但我似乎无法让它在django中工作,无论示例多么简单。 这基本上是基于上面链接中的示例进行的略微修改

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; }); });  

url:

 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:

 
{% csrf_token %}

该表格假设包含一个djangoforms,但由于我甚至无法使基础工作,这将是毫无意义的。 有人提到了csrf_token标签,但删除它也无法解决问题。 上面示例的输出基本上只产生警报(’错误’)而没有别的。 我经历了很多例子,但我甚至无法获得最基本的工作

OK..thx为你的评论..我把它全部整理出来..基本上我错过了{%csrf_token%}和csrfmiddlewaretoken:'{{csrf_token}}’..只是为了那些可能的人的利益读这个……新代码看起来像这样

javascript:

  

html:

 
{% csrf_token %}