2017-10-12 85 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好點 - 更新答案添加一個關於這個 –