Ajax在Djangopost中不起作用
我正在尝试在Django中使用ajax在新闻网站上发表评论。但是它不起作用。 当我单击提交按钮时,它仍然刷新页面,没有像ajax那样没有区别。
我是Django和Ajax的新手。有什么朋友可以帮我解决一下吗?
这是我的view.py:
def newsDetailView(request, news_pk): news = News.objects.get(id=news_pk) title = news.title author = news.author_name add_time = news.add_time content = news.content category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) comment_form = CommentForm(request.POST or None) if request.method == 'POST' and comment_form.is_valid(): if not request.user.is_authenticated: return render(request, 'login.html', {}) comments = comment_form.cleaned_data.get("comment") news_comment = NewsComments(user=request.user, comments=comments, news=news) news_comment.save() return render(request, "news_detail.html", { 'title': title, 'author': author, 'add_time': add_time, 'content': content, 'tags': tags, 'category': category, 'all_comments': all_comments, 'comment_form': comment_form })
这是我的news_detail模板,我获取表单数据:
{% if user.is_authenticated %}
在我的news_detail模板中,我将所有注释呈现给模板:
{% for user_comments in all_comments %} {{ user_comments.user.username }}
{{ user_comments.comments }} {{ user_comments.add_time }} {% endfor %}
这是我在news_detail模板中的Ajax:
$('#js-pl-submit').on('click', function(){ var comments = $("#js-pl-textarea").val() if(comments == ""){ alert("评论不能为空") return false } $.ajax({ cache: false, type: "POST", url:"", data:{'news_pk':{{ news.id }}, '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();//刷新当前页面. } }, }); return false; });
最后这是我的评论的form.py。
def words_validator(comment): if len(comment) < 4: raise ValidationError("亲,最少写两个字") class CommentForm(forms.Form): comment = forms.CharField(widget=forms.Textarea(), validators=[words_validator])
您的绑定不正确,您在表单上有单击处理程序,它应该是一个提交处理程序。 如果您将它绑定到按钮,那么您将使用单击处理程序。
$('#js-pl-submit').on('submit', function(){//<-- here var comments = $("#js-pl-textarea").val() if(comments == ""){ alert("评论不能为空") return false } $.ajax({ cache: false, type: "POST", url:"", data:{'news_pk':{{ news.id }}, '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();//刷新当前页面. } }, }); return false; });
在button
上添加单击事件而不在form
,您必须隐式地将其更改为button
。 默认情况下, button
的类型是提交。
删除表单的id
。 “提交”按钮提交表单数据并重新加载页面。
这可能有效,它包含您的代码中的一些建议。
++ newsDetailView
++在news_details.html中
你脚本中的++
views.py
def newsDetailView(request, news_pk): #news = News.objects.get(id=news_pk) No need to get the object like this anymore news = get_object_or_404(News,id=news_pk) # title = news.title author = news.author_name add_time = news.add_time content = news.content category = news.category tags = news.tag.annotate(news_count=Count('news')) comment_form = CommentForm(request.POST or None) if request.method == 'POST' and comment_form.is_valid(): # if request.method == 'POST' and request.is_ajax() and comment_form.is_valid(): To make sure it's ajax if not request.user.is_authenticated: return JsonResponse({"msg":"You need to login", "url":'login_url','status':'login_required'}) comments = comment_form.cleaned_data.get("comment") news_comment = NewsComments(user=request.user, comments=comments, news=news) news_comment.save() # This needs to be after request.POST process all_comments = NewsComments.objects.filter(news=news) context = { 'title': title, 'author': author, 'add_time': add_time, 'content': content, 'tags': tags, 'category': category, 'all_comments': all_comments, 'comment_form': comment_form, } return render(request, "news_detail.html", context)
news_detail.html | 形成
{% if user.is_authenticated %} {% endif %}
news_detail.html | 评论
JS脚本
$(document).on('submit','#js-pl-submit',function(){ // Correction : Not click, but submit var comments = $("#js-pl-textarea").val() if(!comments){ alert("评论不能为空") return false } $.ajax({ cache: false, type: "POST", url:"", data:{ // 'news_pk':{{ news.id }}, No need to send the news.id /// you are actually on the instance of `news` Object 'comments':comments, 'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val(), // retrieve `csrf_token` from `form` }, async: true, success: function(data) { // Not sure it's the more powerful, but this should work like a charm if(data.status == 'login_url'){ alert(data.msg); window.location.href = data.url; } // Those 2 next lines are useful if you want to refresh without reload the page. $("#js-pl-submit").replaceWith($('#js-pl-submit',data));//刷新当前页面. $("#comments_section").replaceWith($('#comments_section',data)); // This next line will reload the page windows.location.reload(); }, error:function(){ // Codes here in case of error }, statusCode:{ 404:function(){ alert("Object not found"); }, 500:function(){ alert("An error has occured on the server"); }, } }); return false; });
随意发表评论,以便我可以编辑我的答案,帮助您取得成功。
最后我做到了!感谢主!非常兴奋!请在这里查看我的详细答案: Django Ajax表单提交错误地重定向到另一页真的很感谢大家的回复!有了你的回复,我一步一步地想出了这些问题!
{{ user_comments.user.username }}
{{ user_comments.comments }}