weixin_33726318 2018-04-25 03:24 采纳率: 0%
浏览 208

Ajax在Django中不起作用

I'm trying to use ajax in Django to post comment in a news website.However it doesn't work.When I click the submit button,it still refreshes the page and make no difference like no ajax.

I'm really new in Django and Ajax.Any friend can help me solve it?

Here is my 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
    })

Here is my news_detail template where I get form data:

{% if user.is_authenticated %}
<form id="js-pl-submit" method="POST" action="">{% csrf_token %}
{% for field in comment_form %}
{% for error in field.errors %}
<div class="alert alert-warning text-center mb-3" role="alert">{{ error }}</div>
{% endfor %}
{% endfor %}



Here in my news_detail template I render all the comments to the template:

 {% for user_comments in all_comments %}
<img class="mr-3 comment-avatar rounded-circle"src="{{ MEDIA_URL }}{{ user_comments.user.image }}"alt="Generic placeholder image">
<div class="media-body">
<h6 class="mt-0 mb-1">{{ user_comments.user.username }}</h6>
{{ user_comments.comments }}
</div>
<span>{{ user_comments.add_time }}</span>
{% endfor %}

Here is my Ajax in news_detail template:

$('#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;
});

Finally here is my form.py of the comment.

def words_validator(comment):
    if len(comment) < 4:
        raise ValidationError("亲,最少写两个字")


class CommentForm(forms.Form):
    comment = forms.CharField(widget=forms.Textarea(), validators=[words_validator])
  • 写回答

4条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 GEO下载数据的处理报错 :函数‘Meta’标签‘"data.frame"’找不到继承方法,如何解决?
      • ¥15 DLNM模型是否可以用二分类变量作为y变量
      • ¥15 android object box 一个实体多个表怎么写
      • ¥15 temux 启用docker 服务失败
      • ¥15 Flask 使用celery发送邮件出现‘目标计算机积极拒绝‘
      • ¥60 老人用的sd卡在手机里面不知道操作了什么,导致图片和视频变成了文件,取下sd卡连接电脑就是图中的样子,后缀改为.jpg才可以,需要用系统的画图软件才能打开,文件属性还是文件,有没有批量操作的解决办法
      • ¥15 超时跳出方法代码的返回值问题
      • ¥15 汇编语言程序设计设计,ascii码求数,再求数的BCD码
      • ¥30 Mask rcnn训练自己的数据集出现问题!
      • ¥20 研究人工智能时的几个问题