我正在使用Django-Friends
我试图拥有它,以便当用户单击“添加 friend ”时,该按钮会消失(或者理想情况下显示“请求已发送”)。但是,当我单击该按钮时,它不会消失。我是 Django 和 Ajax 的新手,所以我假设这是我的一个错误。最有可能的是 HttpResponse。
这部分实际上让我很困惑。 HttpResponse、render、render_to_response 等。我知道当我想加载模板时可以使用 render 或 render_to_response。但是,如果我不想加载新模板或转到新页面怎么办?就像我希望能够完成添加 friend 或添加页面等操作;全部在一页上。我知道你可以使用 ajax 来做到这一点,但我不知道它的 django 技术方面。
无论如何,这是我的代码。现在,什么也没有发生。该按钮不会消失,也没有发送好友请求。
个人资料.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();
});
});
})
View .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)
最佳答案
这是一个working JSFiddle ,但您不能使用 get
发布数据 {profile_id: profile_id}
,您应该使用 post
或将数据添加为参数,如下所示我做了:
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();
});
});
});
关于javascript - 使用 Ajax 添加好友 - Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31217451/