简体   繁体   中英

How to csrf_token in asynchoronous post with jquery

I found several posts in relation to my question, but none of them solves my problem. I am sending data to the server but I keep getting a 403-error with an error-message that complains about the csrf_token.

Here is my 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>

I created a view and added that view to the urlpatterns-arrau in urls.py. Here is my 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 );
        }
    });

I have tried different ways of including the csrf-token to the data as a seperate object. But nothing works. Any help is appreciated.

Here is the solution I found:

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 );
        }
    });

And in 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' )

I hope this will help somebody someday.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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