【发布时间】:2018-02-03 10:23:33
【问题描述】:
我有一个追随者系统,它是用 ajax 执行的。问题是跟随按钮不起作用。它没有点击,用户数量追随者在一天结束时没有增加。我在下面有我的代码
模板
{% with objects=user.followers.count %}
<span class="count">
<span class="total">
{{ objects }}
</span>
follower{{ objects|pluralize }}
</span>
<a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow button">
{% if request.user not in user.followers.all %}
Follow
{% else %}
Unfollow
{% endif %}
</a>
{% block query %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src=" http://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js "></script>
<script>
var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken);
} }
});
$(document).ready(function(){
$('a.follow').click(function(e){
e.preventDefault();
$.post('{% url "user_follow" %}',
{
id: $(this).data('id'), action: $(this).data('action')
}, function(data){
if (data['status'] == 'ok') {
var previous_action = $('a.follow').data('action');
// toggle data-action $('a.follow').data('action',
previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link text
$('a.follow').text(
previous_action == 'follow' ? 'Unfollow' : 'Follow');
// update total followers
var previous_followers = parseInt(
$('span.count .total').text());
$('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1);
} }
); });
}); </script>
{% endblock %}
然后我在我的 base.html 中提供了块查询
Views.py
def user_follow(request):
user_id = request.POST.get('id')
action = request.POST.get('action')
if user_id and action:
try:
user = User.objects.get(id=user_id)
if action == 'unfollow':
Contact.objects.get_or_create( user_from=request.user, user_to=user)
else:
Contact.objects.filter(user_from=request.user,user_to=user).delete()
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'ko'})
return JsonResponse({'status':'ko'})
如有任何帮助,我们将根据要求提供更多代码。
【问题讨论】:
-
了解的最好方法是在你的 javascript 的不同地方使用
console.log,在你的 python 控制器的不同地方使用print。 -
日志中没有发现错误
-
它不会告诉您错误,它会告诉您代码的哪些部分已到达以及变量的值是什么。
console.log是 javascript 的“打印”函数。 -
你建议我 console.log 或打印哪些部分
-
每一行都试一下,最坏的情况可能要花 1 分钟。