Javascript 将Ajax添加到注释部分不起作用
我试图将Ajax添加到我的评论部分,以避免每次添加评论时页面刷新 因此,我将comments部分从new comments.html加载到post-details.html,并遵循实现Ajax的步骤发布文章,但我的问题是它没有产生任何效果,页面需要刷新以显示新的评论 我在views.py中对Generic DetailView类进行了子分类,并试图找到一种基于URL中接收的参数以JSON格式返回数据的方法。以下是我尝试过的:Javascript 将Ajax添加到注释部分不起作用,javascript,python,jquery,django,ajax,Javascript,Python,Jquery,Django,Ajax,我试图将Ajax添加到我的评论部分,以避免每次添加评论时页面刷新 因此,我将comments部分从new comments.html加载到post-details.html,并遵循实现Ajax的步骤发布文章,但我的问题是它没有产生任何效果,页面需要刷新以显示新的评论 我在views.py中对Generic DetailView类进行了子分类,并试图找到一种基于URL中接收的参数以JSON格式返回数据的方法。以下是我尝试过的: class PostDetailView(DetailView):
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
post = get_object_or_404(Post, slug=self.kwargs['slug'])
comments = Comment.objects.filter(
post=post).order_by('-id')
total_likes = post.total_likes()
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
if self.request.method == 'POST':
comment_form = CommentForm(self.request.POST or None)
if comment_form.is_valid():
content = self.request.POST.get('content')
comment_qs = None
comment = Comment.objects.create(
post=post, user=self.request.user, content=content)
comment.save()
return HttpResponseRedirect("blog/post_detail.html")
else:
comment_form = CommentForm()
context["comments"] = comments
context["comment_form"] = comment_form
context["total_likes"] = total_likes
context["liked"] = liked
if self.request.is_ajax():
html = render_to_string('blog/comments.html', context, request=self.request)
return JsonResponse({'form': html})
else:
return context
以下是回溯:
Traceback (most recent call last):
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 202, in _get_response
response = response.render()
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\response.py", line 105, in render
self.content = self.rendered_content
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content
return template.render(context, self._request)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\backends\django.py", line 59, in render
context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\context.py", line 268, in make_context
raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
在控制台中,我收到以下错误:
GET http://127.0.0.1:8000/blog/blog-4/ 500 (Internal Server Error) jquery.min.js:2
以下是评论部分:
<!-- Submit Comment -->
<div class="container-fluid mt-2">
<div class="form-group row">
<form action="{% url 'blog:post-comment' post.slug %}" method="post" class="comment-form" action=".">
{% csrf_token %}
{{ comment_form.as_p }}
<input type="submit" name="post_id" value='Submit' class="btn btn-outline-success">
<!-- <button type="submit" class="btn btn-outline-success">Submit</button>-->
</form>
</div>
</div>
<!-- Submit Comment -->
<!-- Show Comment -->
<button class="cmt_btn btn btn-outline-info mb-0">Show / Hide {{comments.count}} Comment{{comments|pluralize}}</button>
<div class="comment-box">
{% for comment in comments %}
<ul class="mt-3 list-unstyled">
<li class="media">
<img class="rounded-circle article-img" src="{{ comment.post.author.profile.image.url }}">
<div class="media-body">
<h5 class="mt-0 mb-1">{{comment.user| capfirst}}<small class="text-muted">- {{ comment.created}}</small> </h5>
<hr class="solid mt-0">
{% if comment.user == user %}
<div>
<a class="float-right mr-3" href="{% url 'blog:delete-comment' comment.id%}">Delete </a>
</div>
{% endif %}
{{ comment.content}}
</div>
</li>
</ul>
{% endfor %}
</div>
<!-- Show Comment -->
{%csrf_令牌%}
{{comment_form.as_p}}
显示/隐藏{{comments.count}}注释{{comments | pluralize}
{注释%中的注释为%}
-
{{comment.user | capfirst}}-{{comment.created}
{%if comment.user==user%}
{%endif%}
{{comment.content}
{%endfor%}
这是脚本
<script>
$(document).on('submit', '.comment-form', function(event){
event.preventDefault();
console.log($(this).serialize());
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
$('.main-comment-section').html(response['form']);
$('textarea').val('');
},
error: function(rs, e) {
console.log(rs.responseText);
},
});
});
</script>
$(文档).on('submit','comment form',函数(事件){
event.preventDefault();
log($(this.serialize());
$.ajax({
键入:“POST”,
url:$(this.attr('action'),
数据:$(this).serialize(),
数据类型:“json”,
成功:功能(响应){
$('.main comment section').html(响应['form']);
$('textarea').val(“”);
},
错误:函数(rs,e){
console.log(rs.responseText);
},
});
});
我的问题是:
出现此错误的原因是什么?我如何修复它?函数
获取上下文数据
仅用于为上下文生成数据,而不处理ajax请求。您需要拆分函数以提供GET数据的处理
示例结构
class PostDetailView(详细视图):
型号=员额
template_name=“blog/post_detail.html”#/35;.html
def获取上下文数据(self、*args、**kwargs):
[...]
返回上下文
def get(自我、请求、*args、**kwargs):
如果self.request.is_ajax():
context=self.get_context_数据(self、*args、**kwargs)
html=render_to_string('blog/comments.html',context,request=self.request)
返回JsonResponse({'form':html})
[...]
def post(自我、请求、*args、**kwargs):
[...]
<script>
$(document).on('submit', '.comment-form', function(event){
event.preventDefault();
console.log($(this).serialize());
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
$('.main-comment-section').html(response['form']);
$('textarea').val('');
},
error: function(rs, e) {
console.log(rs.responseText);
},
});
});
</script>