gpt4 book ai didi

javascript - 如何使用ajax函数发送表单而不刷新页面,我错过了什么?我必须为此使用rest-framework吗?

转载 作者:太空狗 更新时间:2023-10-29 20:55:46 25 4
gpt4 key购买 nike

我正在尝试使用 ajax 发送我的评论表单,现在当用户插入评论时整个页面都会刷新。我希望在不刷新页面的情况下很好地插入它。所以我尝试了很多东西但没有运气。因为我是初学者,所以我尝试遵循许多教程链接; https://realpython.com/blog/python/django-and-ajax-form-submissions/ https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/comment-page-1/#comment-1631

我意识到我的问题是我很难在 views.py 和 forms.py 中操作我的代码因此,在进行客户端编程(js 和 ajax)之前,我需要再次设置我的后端(python 代码)以针对 ajax 进行设置。有人可以帮我吗?我不知道如何设置我的后端....

  <div class="leave comment>
<form method="POST" action='{% url "comment_create" %}' id='commentForAjax'>{% csrf_token %}
<input type='hidden' name='post_id' value='{{ post.id }}'/>
<input type='hidden' name='origin_path' value='{{ request.get_full_path }}'/>

{% crispy comment_form comment_form.helper %}
</form>
</div>



<div class='reply_comment'>
<form method="POST" action='{% url "comment_create" %}'>{% csrf_token %}
<input type='hidden' name='post_id' id='post_id' value='{% url "comment_create" %}'/>
<input type='hidden' name='origin_path' id='origin_path' value='{{ comment.get_origin }}'/>
<input type='hidden' name='parent_id' id='parent_id' value='{{ comment.id }}' />
{% crispy comment_form comment_form.helper %}

</form>
</div>

<script>
$(document).on('submit','.commentForAjax', function(e){
e.preventDefault();

$.ajax({
type:'POST',
url:'comment/create/',
data:{
post_id:$('#post_id').val(),
origin_path:$('#origin_path').val(),
parent_id:$('#parent_id').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(json){

我不知道该怎么办...我试过了但是失败了...这里发生了什么})

这是我的forms.py

class CommentForm(forms.Form):
comment = forms.CharField(
widget=forms.Textarea(attrs={"placeholder": "leave your thoughts"})
)

def __init__(self, data=None, files=None, **kwargs):
super(CommentForm, self).__init__(data, files, kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
self.helper.add_input(Submit('submit', 'leave your thoughts', css_class='btn btn-default',))

和我的views.py

def comment_create_view(request):
if request.method == "POST" and request.user.is_authenticated() and request.is_ajax():
parent_id = request.POST.get('parent_id')
post_id = request.POST.get("post_id")
origin_path = request.POST.get("origin_path")
try:
post = Post.objects.get(id=post_id)
except:
post = None

parent_comment = None
if parent_id is not None:
try:
parent_comment = Comment.objects.get(id=parent_id)
except:
parent_comment = None

if parent_comment is not None and parent_comment.post is not None:
post = parent_comment.post

form = CommentForm(request.POST)
if form.is_valid():
comment_text = form.cleaned_data['comment']
if parent_comment is not None:
# parent comments exists
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=parent_comment.get_origin,
text=comment_text,
post = post,
parent=parent_comment
)
return HttpResponseRedirect(post.get_absolute_url())
else:
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=origin_path,
text=comment_text,
post = post
)
return HttpResponseRedirect(post.get_absolute_url())
else:
messages.error(request, "There was an error with your comment.")
return HttpResponseRedirect(origin_path)

else:
raise Http404

即使在阅读了关于它的教程之后,我仍然对使用 ajax 的想法感到非常不安...json 是如何发挥作用的以及我应该如何修改 views.py...有人可以解释一下它们是如何实现的吗聚在一起?帮我完成这件事...

    else:
raise Http404

最佳答案

参见官方文档submit()serialize()并像这样修改你的ajax:

<script>
$('#commentForAjax' ).submit(function(e){
e.preventDefault();

$.ajax({
type:'POST',
url:'comment/create/', // make sure , you are calling currect url
data:$(this).serialize(),
success:function(json){
alert(json.message);
if(json.status==200){
var comment = json.comment;
var user = json.user;
/// set `comment` and `user` using jquery to some element
}
},
error:function(response){
alert("some error occured. see console for detail");
}
});
});

在后端,您将返回 HttpResponseRedirect(),这会将您的 ajax 调用重定向到某个 url(状态代码=302)。我会建议返回任何 json 响应。

对于 Django 1.7+ 添加行 from django.http import JsonResponse 以返回 json 响应

对于 Django 1.7 之前的版本,使用 return HttpResponse(json.dumps(response_data), content_type="application/json")

修改 views.py 的这一部分以返回 Json 响应

def comment_create_view(request):
# you are calling this url using post method
if request.method == "POST" and request.user.is_authenticated():
parent_id = request.POST.get('parent_id')
post_id = request.POST.get("post_id")
origin_path = request.POST.get("origin_path")
try:
post = Post.objects.get(id=post_id)
except:
# you should return from here , if post does not exists
response = {"code":400,"message":"Post does not exists"}
return HttpResponse(json.dumps(response), content_type="application/json")

parent_comment = None
if parent_id is not None:
try:
parent_comment = Comment.objects.get(id=parent_id)
except:
parent_comment = None

if parent_comment is not None and parent_comment.post is not None:
post = parent_comment.post

form = CommentForm(request.POST)
if form.is_valid():
comment_text = form.cleaned_data['comment']
if parent_comment is not None:
# parent comments exists
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=parent_comment.get_origin,
text=comment_text,
post = post,
parent=parent_comment
)
response = {"status":200,"message":"comment_stored",
"user":new_comment.user,
"comment":comment_text,
}
return HttpResponse(json.dumps(response), content_type="application/json")
else:
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=origin_path,
text=comment_text,
post = post
)
response = {"status":200,"message":"new comment_stored",
"user":new_comment.user,
"comment":comment_text,}
return HttpResponse(json.dumps(response), content_type="application/json")
else:
messages.error(request, "There was an error with your comment.")
response = {"status":400,"message":"There was an error with your comment."}
return HttpResponse(json.dumps(response), content_type="application/json")

您不必使用休息框架。但是如果你为此目的使用 rest-framework ,它会很容易实现。

关于javascript - 如何使用ajax函数发送表单而不刷新页面,我错过了什么?我必须为此使用rest-framework吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36217678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com