2017-10-12 48 views
0

我正在创建一个表单,它为一个帖子添加了评论,它没有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')) 
+1

您正在发送POST,但在您的Python代码中,您正在使用GET。你需要在你的ajax中改变POST来GET。 –

+0

@MilanChheda nope,整个事情必须用POST-GET来完成请求必须是幂等的。 –

回答

1

<form>元素使用GET发送请求,并且您的服务器端代码预计值为GET。但是,您的AJAX请求正在使用POST。你需要从

type: 'POST' 

改变AJAX请求类型

type: 'GET' 

或者你可以完全忽略的财产,如jQuery的默认使用GET

或者,您可以保持AJAX方法不变,并修改您的Django代码以接收POST变量。

+0

GET请求__必须是幂等的,并且该视图是关于提交注释的,所以整个事情必须使用POST来完成。 –

+0

@brunodesthuilliers好点 - 更新答案添加一个关于这个 –