2

我有点卡住了,我正在尝试使用 jQuery、Ajax 和 Django 在我的博客中添加一个投票系统,但我没有找到最好的方法。

以下是我的问题:

  1. 如何在我的 jQuery 脚本中获取必须作为 .post 方法中的参数发送的{{ blog.id }} ?
  2. 在我的 jQuery 脚本中,如何找到用于更改投票图像的{% static %}路径?

这是我得到的,到目前为止...

投票.html

<a>Total: {{ total_votes }} </a>
<input type="hidden" name="blog_id" value={{ blog.id }}>
<div class="vote-buttons">
{% if vote.up %}
    <img class="vote-up selected" src="{%static "assets/images/up_on.png"%}"/>
{% else %}
    <img class="vote-up" src="{% static "assets/images/up_off.png" %}"/>
{% endif %}
{% if vote.down %}
    <img class="vote-down selected" src="{%static "assets/images/down_on.png"%}"/>
{% else %}
    <img class="vote-down" src="{% static "assets/images/down_off.png" %}"/>
{% endif %}
</div>

jQuery/Ajax

$(document).ready(function(){
    $('.vote-up, .vote-down').css('cursor', 'pointer');
    $('div.vote-buttons img.vote-up').click(function(){
        if($(this).hasClass('selected')){
            $.post('myurl', {params:params}, function(response){
                $(this).removeAttr('src')
                   .attr('src',"...") # how to get the template {% static %} path?
                   .removeClass('selected');
            });
        }else{
            # when vote isn't selected
        }
    });
});
4

2 回答 2

2

{{ blog.id }}将成为名为 blog_id 的隐藏输入的值,因此您可以像这样找到它

$('input[name="blog_id"]').val();

通过查看其中一张图像的 src 可以找到静态路径。

尝试$('.vote-up').attr('src').replace('assets/images/up_off.png','');

您也可以只创建 javascript 变量来为您处理模板中的值。

<script>
    var blog_id = {{ blog.id }};
    var static_path = "{% static "assets/images/" %}"
</script>

并参考这些值。

于 2013-09-28T12:11:53.193 回答
0

我找到了解决方案,找到我使用的每个 blog.id 的唯一 id:

var id = $('input[name="blog_id"]', $(this)).val();

正如@DGS 所说,要找到我使用的静态路径:

<script>
    var static_path = "{% static "assets/images/" %}"
</script>
于 2013-09-28T13:24:09.397 回答