繁体   English   中英

如何使用jquery在异步帖子中使用csrf_token

[英]How to csrf_token in asynchoronous post with jquery

我找到了几个与我的问题有关的帖子,但没有一个能解决我的问题。 我正在向服务器发送数据,但我不断收到 403 错误和错误消息,抱怨 csrf_token。

这是我的 html:

            <ul id="EditorNav" class="editor-nav">
                <form id="NavItemsEditorForm" class="nav-items-editor-form">
                    {% csrf_token %}
                        <!-- {{ form }} -->
                    {% for item in pages %}
                        <input class="editor-nav-input" type="text" value="{{ item }}"/>
                    {% endfor %}
                </form>
                <img id="Plus" class="plus" src="{% static 'img/plus.png' %}" alt="Plus" title="Een menu-item toevoegen" />
                <img id="Shuffle" class="shuffle" src="{% static 'img/shuffle.png' %}" alt="Shuffle" title="Verander de volgorde van de menu-items" />
                <button id="NavEditReady" class="nav-edit-ready">Klaar</button>
            </ul>

我创建了一个视图并将该视图添加到 urls.py 中的 urlpatterns-arrau。 这是我的javascript:

    jQuery.each( jQuery( '.editor-nav-input' ), function( i ){
        let data = {}

        if( jQuery( this ).val() === '' )
        {
            jQuery( this ).remove();
        }else{
            const idx = jQuery( '.editor-nav-input' ).index( this );
            const tekst = jQuery( '.editor-nav-input' ).eq( idx ).val(); 

            data = {
                "id": idx,
                "tekst": tekst,
                "href": tekst.replace(/\s/g, '_').toLowerCase(),
                "volgorde": idx + 1,
            };
            formdata.push( data );
        }
    });
    console.log( formdata );

    // Stuur de data naar de server:

    jQuery.ajax({
        method: "POST",
        url: "/pagepost/",
        headers: { 'X-CSRFToken': '{{ csrf_token }}' },
        data: formdata,
        dataType: "json",
        success: function( response ){
            console.log(response);
        },
        error: function( err ){
            console.log( err.responseText );
        }
    });

我尝试了不同的方法将 csrf-token 作为单独的对象包含在数据中。 但没有任何作用。 任何帮助表示赞赏。

这是我找到的解决方案:

Javascript:

    jQuery.ajax({
        method: "POST",
        url: "/pagepost/",
        headers: { "X-CSRFToken": jQuery('input[name=csrfmiddlewaretoken]').val() },
        data: formdata,
        dataType: "json",
        success: function( response ){
            console.log(response);
        },
        error: function( err ){
            console.log( err.responseText );
        }
    });

在 views.py 中:

def PagesPost(request):
    if request.method == 'POST':
        tekst = request.POST.get( 'tekst' )
        href = request.POST.get( 'href' )
        volgorde = request.POST.get( 'volgorde' )

        return HttpResponse( 'Success' )

我希望有一天这会对某人有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM