单击按钮后如何将 Django 对象 ID 传递给 jquery/ajax?

How to pass django object id to jquery/ajax upon click of a button?

我正在尝试使用 jquery/ajax 实现类似 reddit 的投票系统。如何通过单击按钮传递每个人 Post 的对象 id

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

<script>
    # Somehow need to distinguish between upvote/downvote and include object id
    $(?).click(function () {
        var id = id
        $.ajax({
            url: '/ajax/upvote/',
            data: {
                'id': id
            }
        });
    });
</script>

可以将 id 作为属性添加到带有 data-id 的每个按钮标签中。要知道哪种类型的投票,您也可以将其添加到数据属性 data-vote

{% 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 %}

并在 class .vote 中添加事件 .vote with js:

<script>
# Somehow need to distinguish between upvote/downvote and include object id
$(".vote").click(function () {
    var id = $(this).data("id"),
        vote_type = $(this).data("vote");
    $.ajax({
        url: '/ajax/upvote/',
        data: {
            'id': id,
            'vote_type':vote_type,
        }
    });
});

如果你想要两个不同的端点,你可以为按钮使用 onclick 属性。如果您希望将投票类型作为参数发送到同一端点,您可以在点击事件中作为第二个参数调用。

{% for post in posts %}
    <h2>{{ post.title }}</h2>
    {{ post.upvotes }}<button onclick="upvote({{post.id}});" class="upvote" type="submit">Upvote</button>
    {{ post.downvotes }}<button onclick="downvote({{post.id}});" class="downvote" type="submit">Downvote</button>
{% endfor %}

<script>
    function upvote (post_id) {
        $.ajax({
            url: '/ajax/upvote/',
            data: {
                'id': post_id
            }
        });
    }
    function downvote(post_id) {
        $.ajax({
            url: '/ajax/downvote/',
            data: {
                'id': post_id
            }
        });
    }
</script>