我正在創建一個表單,它爲一個帖子添加了評論,它沒有ajax工作,因爲ajax將表單數據發送爲None。ajax與django不兼容
的AJAX:
<script>
$(function() {
$("#myform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
confirm('worked')
}
});
});
});
</script>
形式:
<form action="{% url 'newcom' Post.id%}" id="myform">
<div class="input-group">
<input type="text" name="comment_body" class="form-control" placeholder="Leave a comment">
<div class="input-group-btn">
<button class="btn btn-success" id="message" type="submit">
<i class="glyphicon glyphicon-send"></i>
</button>
</div>
</div>
<br>
</form>
視圖:
def new_comment(request, post_id):
body = request.GET.get('comment_body')
post = Post.objects.get(id=post_id)
Nat.objects.create(fromUser=request.user.username, toUser=post.created_by, content="commented on your post")
Comment.objects.create(post=post, created_by=request.user,
created_at=timezone.localtime(timezone.now()), comment=body)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
您正在發送POST,但在您的Python代碼中,您正在使用GET。你需要在你的ajax中改變POST來GET。 –
@MilanChheda nope,整個事情必須用POST-GET來完成請求必須是冪等的。 –