jquery 如何在JavaScript中使用{% csrf_token %}

34gzjxbg  于 2023-06-22  发布在  jQuery
关注(0)|答案(4)|浏览(138)

在我的用户页面中,我用ajax进行了编辑。当我点击编辑,它工作正常。但是当我提交表单时,它什么也不做。当我检查时,这是错误:
CSRF verification failed. Request aborted.
那么,如何在我的javascript中放置{% csrf_token %}?请咨询。谢谢你。
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:

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

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)
35g0bw71

35g0bw711#

您没有发送服务器生成的csrf_token用于POST以验证数据的有效性。所以才有错误。
作为请求的data部分的一部分,您需要发送令牌

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()

如果要将整个表单作为字典发送

7z5jn7bk

7z5jn7bk2#

var csrftoken = Cookies.get('csrftoken ');
xhr.setRequestHeader(“X-CSRFToken”,csrftoken);
enter link description here

20jt8wwn

20jt8wwn3#

这是我用的。不确定它是否适用于你的情况。

// sending a csrftoken with every ajax request
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});
i7uq4tfw

i7uq4tfw4#

var CSRF_TOKEN = '{{ csrf_token }}';

过去这是js文件

相关问题