使用Ajax添加好友-Django

Add Friend with Ajax - Django

本文关键字:-Django 好友 添加 Ajax 使用      更新时间:2023-09-26

我正在使用Django Friends

我正在尝试使用它,这样当用户点击添加好友时,按钮就会消失(或者理想情况下会显示请求已发送(。然而,当我点击按钮时,它并没有消失。我是Django和Ajax的新手,所以我认为这是我的一个错误。很可能是HttpResponse。

那部分实际上让我很困惑。HttpResponse、render、render_to_response等。我知道当我想加载模板时,我可以使用render或render_to_response。但是,如果我不想加载新模板或转到新页面,该怎么办?就像我想能够完成一个动作,比如添加一个朋友,或者添加一个页面,等等;所有内容都在一页上。我知道你可以用ajax来做这件事,但我不知道django的技术方面

不管怎样,这是我的密码。现在,什么都没发生。按钮不会消失,也不会发送交友请求。

profile.html

    <div class="text-center">
      <div>
        "{{currUserprofile.tagline}}"
      </div>
      {{currUser.profile.city}}, {{currUser.profile.state}}
      {{currUser.id}}
    </div>
    <!-- <button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
 -->    <!--Find a way to signify looking or not looking to mentor -->
      <button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>

ajax.js

    $(document).ready(function () {
    $('#addfriend').click(function () {
        var profile_id = $(this).data("profileid");
        $.get('/myapp/addfriend/id=' + profile_id, function (data) {
            $('#addfriend').fadeOut();
        });
    });
})

views.py

@login_required
def profile(request, id):
    context = RequestContext(request)
    currUser = User.objects.get(pk = id)
    profile = UserProfile.objects.filter(user = currUser)
    return render_to_response('myapp/profile.html', {'currUser': currUser, 'UserProfile': UserProfile}, context)

@login_required
def addfriend(request, id):
    context = RequestContext(request)
    other_user = User.objects.get(pk=id)
    new_relationship = Friend.objects.add_friend(request.user, other_user)
    profile = UserProfile.objects.filter(user = other_user)
    return HttpResponse(new_relationship)

这里有一个正在工作的JSFiddle,但你不能用get发布数据{profile_id: profile_id}——你应该使用post或将数据添加为params,就像我所做的那样:

HTML:

<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>

JS:

$(document).ready(function () {
    $('#addfriend').click(function () {
        var profile_id = $(this).data("profileid");
        $.get('/myapp/addfriend/?profile_id=' + profile_id, function (data) {
            $('#addfriend').fadeOut();
        });
    });
});