Django / Ajax不刷新

I have built a Save button. The user clicks the "Save" button to save a record to their collection. This changes the "Save" button text to "Saved". The user can then click on "Saved" to unsave the record.

The user can Save the record succesfully and the ajax updates the html as expected by changing id="likes" to id="unsave".

The issue is that the ajax is not picking up the id="unsave" so is not routing to the unsave_release URL, it is routing to the save_release URL.

Url examples

http://127.0.0.1:8000/save_release/?release_id=585197&num_saves=14 http://127.0.0.1:8000/unsave_release/?release_id=585197&num_saves=14

Do I need to reset the ajax in some way after the user makes the initial Save?

Models.py

@login_required
def save_release(request):

    release_id = None
    num_saves = None
    username = request.user.username
    if request.method == 'GET':
        release_id = request.GET['release_id']
        num_saves = request.GET['num_saves']

    if release_id:

        insert = ChartsExtended(release_id=release_id,artist=username,url='Like',date='date',type='U',source='net')
        insert.save()
        num_saves = str(int(num_saves) + 1)
        return HttpResponse(num_saves)

@login_required
def unsave_release(request):

    release_id = None
    num_saves = None
    username = request.user.username
    if request.method == 'GET':
        release_id = request.GET['release_id']
        num_saves = request.GET['num_saves']

    if release_id:

        insert = ChartsExtended.objects.get(release_id=release_id,artist=username)
        insert.delete()
        num_saves = str(int(num_saves) - 1)
        return HttpResponse(num_saves) 

ajax.js

$(document).ready(function() {

        // JQuery code to be added in here.
        $('#likes').click(function(){
            var release_id;
            var num_saves;
            release_id = $(this).attr("data-releaseid");
            num_saves = $(this).attr("data-numsaves")
            $.get('/save_release/', {release_id: release_id,num_saves: num_saves}, 

                function(data){

                $('#like_count').html(data + " people saved this");

                // $('#likes').css({"background-color":"#FF0000"});

                $('#likes').toggleClass("btn-info");
                $('#likes').text('Saved!')
                $('#likes').attr('id','unsave');
            });
        });

        //this unsaves a release from Release
        $('#unsave').click(function(){
            var release_id;
            var num_saves;
            release_id = $(this).attr("data-releaseid");
            num_saves = $(this).attr("data-numsaves")
            $.get('/unsave_release/', {release_id: release_id,num_saves: num_saves}, 

                function(data){

                $('#like_count').html(data + " people saved this");

                // $('#likes').css({"background-color":"#FF0000"});

                $('#unsave').toggleClass("btn-success");
                $('#unsave').text('Save')
                $('#unsave').attr('id','likes');
            });
        });

release.html

<h3 id="like_count">{{dict_item.cnt}} people saved this</h3>


  <p><button id="likes" data-releaseid="{{ dict_item.id }}" data-numsaves="{{dict_item.cnt}}" class="btn btn-xlarge btn-success release-follow-buttons" type="button">Save</button></p>

which transforms into the following after the user clicks Save

<p><button id="unsave" data-releaseid="release_id" data-numsaves="num_saves" class="btn btn-xlarge btn-success release-follow-buttons btn-info" type="button">Saved!</button></p>

urls.py

url(r'^save_release/$', views.save_release, name='save_release'),
url(r'^unsave_release/$', views.unsave_release, name='unsave_release'),

1个回答


这是因为,当您在ID为 unsave </ code>的元素上附加 onclick </ code>处理程序时,该处理程序当时不存在且未附加处理程序。 </ p>

在更改 id </ code>时,您需要附加处理程序,或者如果使用委派的事件处理程序。</ p>

  $(document).on(“ click”,“ #likes”,function(){
     //代码
});
$(document).on(“ click”,“ #unsave”,function(){
     //代码
});
</ code> </ pre>

您也不需要在您的 ready </ code>回调中附加这些委托事件,因为对于 #likes </ code>和 #unsave 而言并不必要 code>时存在的元素。</ p>
     </ div>

展开原文

原文

It's because when you are attaching the onclick handler on the element with the id unsave, which at that time doesn't exist and the handler isn't attached.

You either need to attach the handler, when you change the id or a better solution would be if you use delegated event handlers.

$(document).on("click", "#likes", function() {
    // code
});
$(document).on("click", "#unsave", function() {
    // code
});

You also don't need to attach these delegated events in your ready callback, because it isn't necessary for #likes and #unsave elements to exist when you do that.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐