Django 1.10 - Ajax - 操作顺序?

时间:2017-04-14 07:43:02

标签: javascript jquery python ajax django

我正在使用Ajax和Django 1.10在我的网站上实现类似功能(用户喜欢由其他用户发布的图像)。我有以下代码:

观点文件:

@ajax_required
@login_required
@require_POST
def image_like(request):
    image_id = request.POST.get('id')
    action = request.POST.get('action')
    if image_id and action:
        try:
            image = Image.objects.get(id=image_id)
            if action == 'like':
                image.users_like.add(request.user)

            else:
                image.users_like.remove(request.user)
            return JsonResponse({'status':'ok'})
        except:
                pass
    return JsonResponse({'status':'ko'})


def image_detail(request, id, slug):
    image = get_object_or_404(Image, id=id, slug=slug)
    return render(request,
    'images/image/detail.html',
    {'section': 'images',
    'image': image})

在base.html中:

    <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(){
            {% block domready %}
            {% endblock %}
        });
    </script>

并在detail.html中完成:

{% extends "base.html" %}
{% block title %}{{ image.title }}{% endblock %}
{% block content %}

...

 {% with total_likes=image.users_like.count users_like=image.users_like.all %}
            <div class="image-info">
                <div>
                    <span class="count">
                        <span class="total">{{ total_likes }}</span>
                        like{{ total_likes|pluralize }}
                    </span>
                    <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button">
                        {% if request.user not in users_like %}
                            Like
                        {% else %}
                            Unlike
                        {% endif %}
                    </a>
                </div>
            {{ image.description|linebreaks }}
            </div>
            <p> Image liked by :</p>
            <div class="image-likes">

                {% for user in image.users_like.all %}
                    <div>
                        <p>{{ user.last_name }}</p>
                    </div>
                    {% empty %}
                    Nobody likes this image yet.
                {% endfor %}
            </div>
        {% endwith %}
    {% endblock %}

    {% block domready %}
        $('a.like').click(function(e){
            e.preventDefault();

            $.post('{% url "images:like" %}',
                {
                    id: $(this).data('id'),
                    action: $(this).data('action')
                },
            function(data){
                if (data['status'] == 'ok')
                {
                    var previous_action = $('a.like').data('action');

                    // toggle data-action
                    $('a.like').data('action', previous_action == 'like' ?
                    'unlike' : 'like');

                    // toggle link text
                    $('a.like').text(previous_action == 'like' ? 'Unlike' :
                    'Like');// update total likes
                    var previous_likes = parseInt($('span.count .total').text());
                    $('span.count .total').text(previous_action == 'like' ?
                    previous_likes + 1 : previous_likes - 1);
                }
              }
            );
        });
    {% endblock %}

虽然我主要理解代码本身,但我需要帮助理解请求,回调函数和其他所有内容的执行顺序......例如:用户单击 like button ,信息被传递到服务器,它被操纵,数据库修改,发回,页面改变......

告诉我是否需要任何额外的代码(模型,网址等)。无法发布所有内容。

0 个答案:

没有答案