【问题标题】:Change button after submit - jquery, django提交后更改按钮 - jquery,django
【发布时间】:2016-03-30 07:03:11
【问题描述】:

我有一个 ajax“关注”按钮。它工作正常,提交按钮的属性disabled 后变为"disabled"。但我想在提交后将“关注”按钮更改为“取消关注”按钮,就像在 Twitter 中一样。这个怎么做?我试过这个来改变按钮的属性“form”来提交另一个表单:

success:function(){
                $button.attr('form','unfollow');

但不幸的是它不起作用。

模板event.html:

   {% if user in event.users.all %}
            <form id="unfollow">
            {% csrf_token %}
            <input type="hidden" value="{{ event.id }}" name="remove">
            <button type="submit" class="btn btn-warning btn-block">{% trans "Unfollow"%}</button>
            </form>
    {% else %}
            <form id="follow">
            {% csrf_token %}
            <input type="hidden" value="{{ event.id }}" name="add">
            <button type="submit" class="btn btn-primary btn-block">{% trans "Follow"%}</button>
            </form>
    {% endif %}

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
    <script type="text/javascript">

    $(document).on('submit','#unfollow', function(e){
        var $button = $(this).find('button');
        e.preventDefault();
        $.ajax({
            url:'/event/{{ event.id }}/',
            data: "remove={{ event.id }}",
            success:function(){
                $button.attr('disabled', 'disabled').text('{% trans "Unfollowed" %}');
            }
        })
    });

    $(document).on('submit','#follow', function(e){
        var $button = $(this).find('button');
        e.preventDefault();
        $.ajax({
            url:'/event/{{ event.id }}/',
            data: "add={{ event.id }}",
            success:function(){
                 $button.attr('disabled', 'disabled').text('{% trans "Followed" %}');
            }
        })
    });

</script>

views.py

user = request.user
if request.GET.get('add'):
    event.users.add(user)
    event.save()
if request.GET.get('remove'):
    event.users.remove(user)
    event.save()

【问题讨论】:

    标签: jquery ajax django


    【解决方案1】:

    这里的一个主要问题是您有两个端点(关注/取消关注)进行非常相似的处理。

    首先,为了简化一切,您可以使用一个端点来切换状态(从关注到取消关注,反之亦然)。多亏了这一点,您将只能使用单一表单发送事件 ID。

    我根本不是 python 人,但一切都应该是这样的:

    views.py

    user = request.user
    if request.GET.get('eventId'):
        # if the user is in event.users, then remove it, otherwise, add it (sorry I don't know the Python syntax here, but it is quite a simple condition).
        # The algorithm would be like this:
        # isFollowing = user in event.users
        # if (isFollowing) then event.users.remove(user)
        #     else event.users.add(user)
        event.save()
        # Next, return JSON (see how to do it with Django):
        # return {"following": !isFollowing}
    

    template.html

    <form class="formFollowEvent"> <!-- Based on a class and not an ID, in case you want to have multiple follow / unfollow buttons on a same page, even for different events -->
        {% csrf_token %}
        <input type="hidden" value="{{ event.id }}" name="eventId">
        <button type="submit" class="btn btn-warning btn-block">
            {% if user in event.users.all %}
                {% trans "Unfollow" %}
            {% else %}
                {% trans "Follow" %}
            {% endif %} <!-- There should be something better with your template engine to handle the follow / unfollow translation -->
        </button>
    </form>
    

    JS

    $('.formFollowEvent').on('submit', function(e) {
        e.preventDefault();
    
        var $this = $(this);
        var $button = $this.find('button[type="submit"]');
        var eventId = $this.find('input[name="eventId"]').val();
    
        $.ajax({
            url:'/switchStatus',
            data: {
                eventId: eventId
            },
            success:function(data){
                 $button.text((!!data.following) ? {% trans "Unfollow"%} : {% trans "Follow"%});
            }
        })
    });
    

    这是一个 jsFiddle 来说明我所说的:https://jsfiddle.net/1u39dhjh/

    注意:您应该检查如何使用 Django 通过 Ajax 正确发送表单,因为您不在这里发送 csrf 令牌。

    希望我的回答对你有所帮助。

    【讨论】:

    • 你的解决方案比我的好。 data.status 来自哪里?我认为视图返回的代码应该是:{'status': 'following'} 或(更好?)JS:data.following(布尔值)而不是data.status == 'following'
    • 我的错,我在 JS 中写了“data.status”而不是“data.following”。我修好了它。你也可以使用布尔值,这取决于你。
    • 是的,你在你的 Django 视图中返回一个布尔值(它被注释了,但是:return {"following": !isFollowing})。您应该对齐代码。要么不返回布尔值而是“跟随”,要么在 JS 代码中检查布尔值。
    【解决方案2】:

    您可以简单地添加两个表单,总是这样,然后像这样适当地隐藏/显示:

    <form id="unfollow" {% if user not in event.users.all %}style="display:none;"{% endif %}>
        {% csrf_token %}
        <input type="hidden" value="{{ event.id }}" name="remove">
        <button type="submit" class="btn btn-warning btn-block">{% trans "Unfollow"%}</button>
    </form>
    
    <form id="follow"% if user in event.users.all %}style="display:none;"{% endif %}>
        {% csrf_token %}
        <input type="hidden" value="{{ event.id }}" name="add">
        <button type="submit" class="btn btn-primary btn-block">{% trans "Follow"%}</button>
    </form>
    

    把你的 JS 改成:

    success: function() {  // in your follow form
        $followForm.hide();
        $unfollowForm.show();
    }
    
    success: function() {  // in your unfollow form
        $unfollowForm.hide();
        $followForm.show();
    }
    

    您还可以使用一些状态变量来决定隐藏哪个表单以及显示哪个表单。

    旁注: 对于更改状态的提交,您应该更喜欢 POST 而不是 GET。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-03
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      相关资源
      最近更新 更多