如何在Django视图中使用jquery / ajax传递的值

时间:2018-08-14 00:34:57

标签: ajax django

如何检索和使用通过ajax传递给视图的数据?在此示例中,我尝试实现类似upvote / downvote系统的reddit

html / js:

{% for post in posts %}
    <h2>{{ post.title }}</h2>
    {{ post.upvotes }}<button data-id="{{post.id}}" data-vote="up" class="vote" type="submit">Upvote</button>
    {{ post.downvotes }}<button data-id="{{post.id}}" data-vote="down"  class="vote" id="downvote" type="submit">Downvote</button>
{% endfor %}

      <script>
          $(".vote").click(function () {
              var id = $(this).data("id"); //get data-id
              var vote_type = $(this).data("vote"); //get data-vote
          };
          $.ajax({
              url: '/ajax/upvote/',
              data: {
                  'id': id,
                  'vote_type':vote_type,
              }
          });
      </script>

urls.py:

url(r'^ajax/upvote/$', views.upvote, name='upvote'),

视图:

def upvote(request):
    #how do i use 'id' and 'vote_type' values here?

1 个答案:

答案 0 :(得分:1)

您需要先编辑JavaScript以发送csrf令牌,然后在url.py中注册POST网址。

{% for post in posts %}
    <h2>{{ post.title }}</h2>
    {{ post.upvotes }}<button data-id="{{post.id}}" data-vote="up" class="vote" type="submit">Upvote</button>
    {{ post.downvotes }}<button data-id="{{post.id}}" data-vote="down"  class="vote" id="downvote" type="submit">Downvote</button>
{% endfor %}

      <script>
          $(".vote").click(function () {
              var id = $(this).data("id"); //get data-id
              var vote_type = $(this).data("vote"); //get data-vote
          };
          $.ajax({
              url: '/ajax/upvote/',
              data: {
                  'id': id,
                  'vote_type':vote_type,
                  csrfmiddlewaretoken: '{{ csrf_token }}'
              }
          });
      </script>

现在,您可以按照常规方式访问在views.py中发送的数据:

def upvote(request):
    sentence= request.POST.get("id","")
    upvote = request.POST.get("upvote","") 
    #continue doing your stuffs here...

希望这会有所帮助。