终于我做到了!感谢上帝!非常兴奋!
我以前的代码中有三个主要问题。
首先:由于ajax会将news_pk发布到视图 update_comment
,所以我不需要在此视图的url和template(在
<form>tag的url和ajax的url中)中添加news_pk
,所以我删除了它们或数据仍会通过Form,但不会通过Ajax。
第二:我的绑定不正确,我在表单上有单击处理程序,应该是提交处理程序。如果将其绑定到按钮,则可以使用单击处理程序。但是对于这一部分,我仍然有些困惑,在按钮顶峰方式和表单提交方式之间。
第三个问题是我误认为’comments’和’comment’。’comment’是的name属性
<textarea>,forms.py通过该属性获取数据。
注释是由ajax定义的,
var comments=$("#js-pl-textarea").val(),因此在视图中我需要使用
comments= request.POST.get("comments", "")但不需要注释,这就是“发布失败”的原因。
以下是我的代码。
这是ajax:
$("#comment_form").submit(function(){ var comments = $("#js-pl-textarea").val() $.ajax({ cache: false, type: "POST", url:"{% url 'operation:update_comment' %}", data:{'news_pk':{{ news.pk }}, 'comments':comments}, async: true, beforeSend:function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success: function(data) { if(data.status == 'fail'){ if(data.msg == '用户未登录'){ window.location.href="login"; }else{ alert(data.msg) } }else if(data.status == 'success'){ window.location.reload();//refresh current page. } }, }); return false; });
这是我的udate_comment视图:
@login_requireddef update_comment(request): news_pk = request.POST.get("news_pk", 0) comments = request.POST.get("comments", "") if int(news_pk) > 0 and comments: news_comments = NewsComments() news = News.objects.get(id=int(news_pk)) news_comments.news = news news_comments.comments = comments news_comments.user = request.user news_comments.save() return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json') else: return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')
这是模板中的表格:
<form id="comment_form" action="{% url 'operation:update_comment'%}" method="POST" >{% csrf_token %}<textarea id="js-pl-textarea"name="comment"></textarea><input type="submit" value="Submit"> </input></form>
非常感谢大家的回覆!有了您的回覆,我逐步找出了这些问题!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)