【问题标题】:Voting system with Django, jQuery and Ajax使用 Django、jQuery 和 Ajax 的投票系统
【发布时间】:2013-09-28 11:55:21
【问题描述】:

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

这是我的问题:

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

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

votes.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
        }
    });
});

【问题讨论】:

    标签: jquery ajax django


    【解决方案1】:

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

    并引用这些值。

    【讨论】:

    • 谢谢,$('input[name="blog_id"]').val(); 返回 blog.id 的最后一个 id 而不是选中的那个,我错过了什么吗?
    • 问题是我在一个循环中,所以显示了很多票。这就是我得到最后一个 blog.id 的原因。 jQuery中有没有办法找到$(this)选定的输入?
    【解决方案2】:

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

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

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

    <script>
        var static_path = "{% static "assets/images/" %}"
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多