如何在javascript中使用{%csrf_token%} [英] How to use {% csrf_token %} in javascript

查看:589
本文介绍了如何在javascript中使用{%csrf_token%}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的用户页面中,我使用ajax进行编辑。当我点击编辑时,它工作正常。但是当我提交表格时,它什么也没做。当我选中时,这是错误:

In my users page, i have in place editing with ajax. And when i click edit, it works fine. But when i submit the form, it don't do anything. When i checked, this is the error:

CSRF验证失败。请求已中止。

那么,如何在我的javascript中放置{%csrf_token%}?请指教。
谢谢。

So, how do I place {% csrf_token %} in my javascript? Please advice. Thank you.

edit.js:

function bookmark_edit() {
    var item = $(this).parent();
    var url = item.find(".title").attr("href");
    item.load("/save/?ajax&url=" + escape(url), null, function () {
        $("#save-form").submit(bookmark_save);
        });
    return false;
    }

$(document).ready(function () {
    $("ul.bookmarks .edit").click(bookmark_edit);
    });

function bookmark_save() {
    var item = $(this).parent();
    var data = {
        url: item.find("#id_url").val(),
        title: item.find("#id_title").val(),
        tags: item.find("#id_tags").val()
        };
    $.post("/save/?ajax", data, function (result) {
        if (result != "failure") {
        item.before($("li", result).get(0));
        item.remove();
        $("ul.bookmarks .edit").click(bookmark_edit);
        }
        else {
            alert("Failed to validate bookmark before saving.");
        }
        })
        return false;
    }

save_form.html:

save_form.html:

<form id = "save-form" method="post" action="/save/">
{% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Save" />
</form>

user_page.html:

user_page.html:

{% extends "base.html" %}
{% block external %}
    <script type = "text/javascript" src="{% static "assets/js/bookmark_edit.js" %}"></script>
{% endblock %}
{% block title %} {{username}} {% endblock %}
{% block head %} Bookmarks for {{username}} {% endblock %}
{% block content %}
    {% include "bookmark_list.html" %}
{% endblock %}

view.py:

@login_required(login_url='/login/')
def bookmark_save_page(request):
    ajax = request.GET.has_key('ajax')
    if request.method == 'POST':
        form = BookmarkSaveForm(request.POST)
        if form.is_valid():
            bookmark = _bookmark_save(request, form)
            if ajax:
                variables = RequestContext(request, {
                    'bookmarks':[bookmark],
                    'show_edit':True,
                    'show_tags':True
                    })
                return render_to_response('bookmark_list.html', variables)
            else:
                return HttpResponseRedirect('/user/%s/' % request.user.username
                    )
        else:
            if ajax:
                return HttpResponseRedirect('failure')
    elif request.GET.has_key('url'):
        url = request.GET['url']
        title = ''
        tags = ''

        try:
            link = Link.objects.get(url=url)
            bookmark = Bookmark.objects.get(
                link=link,
                user = request.user
                )
            title = bookmark.title
            tags = ' '.join(
                tag.name for tag in bookmark.tag_set.all()
                )
        except ObjectDoesNotExist:
            pass
        form = BookmarkSaveForm({
            'url':url,
            'title':title,
            'tags':tags
            })
    else:
        form = BookmarkSaveForm()

    variables = RequestContext(request, {
        'form': form
        })
    if ajax:
        return render_to_response(
            'bookmark_save_form.html',
            variables
            )
    else:
        return render_to_response('bookmark_save.html',variables)


推荐答案

您没有为POST发送服务器生成的csrf_token以验证数据的有效性。因此错误。

You are not sending the server generated csrf_token for the POST to verify the validity of the data. Hence the error.

作为请求中数据部分的一部分,您需要发送令牌

As a part of the data part of the request, you need to send the token

csrfmiddlewaretoken: '{{ csrf_token }}' 

这样的东西

var data = {
    url: item.find("#id_url").val(),
    title: item.find("#id_title").val(),
    tags: item.find("#id_tags").val(),
    csrfmiddlewaretoken: '{{ csrf_token }}' 
};

或者您可以这样做:

var data = $('form').serialize()

如果你想把整个表格作为字典发送

if you want to send the whole form as a dictionary

这篇关于如何在javascript中使用{%csrf_token%}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆