简体   繁体   English

django 使用经典的 javascript 将 AJAx POST 请求发送到带有 csrf_token 的服务器,如何?

[英]django sending AJAx POST request using classical javascript into server with csrf_token, how to?

I have this part of code:我有这部分代码:

document.querySelector('#form_pizza_order').onsubmit = () => {

    // make an ajax request to save the pizza order in the server
   const request = new XMLHttpRequest();
   request.open('POST', '/order_pizza');

   // Callback function for when request completes
   request.onload = () => {
       const data = JSON.parse(request.responseText);

       if (data.success) {
        // show in cart new order
        show_in_cart(data);
       }
       else {
           alert('failed to save pizza order in server');
       }
   }

   const data = new FormData();
   let username = localStorage.getItem('username');
   data.append('username', username);

   //Send request
   request.send(data);
   return false;
};

that when used the server returns 403 forbidden response because of csrf_token not sent.使用时,由于未发送 csrf_token,服务器返回 403 禁止响应。 how do I add the crsf_token header properly with the javascript above, without using jquery.如何在不使用 jquery 的情况下使用上面的 javascript 正确添加 crsf_token header。 just javascript.只是 javascript。

thanks.谢谢。

function sendData(){
    const XHR = new XMLHttpRequest();
    // Set up our request
    XHR.open("POST", "{% url 'test:index' %}" );
    XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
    // Bind the FormData object and the form element
    let FD = new FormData(form);
    // append the token
    FD.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    // The data sent is what the user provided in the form
    XHR.send(FD);
}

let form = document.getElementById('<form_id>')

//  take over its submit event.
form.addEventListener("submit", function (event) {
    console.log('Submited!')
    event.preventDefault();
    sendData();
})

In your django views, you can test if the request is ajax:在您的 django 视图中,您可以测试请求是否为 ajax:

def index(request):
    if request.is_ajax() and request.method='POST':
        print(request.POST)
        # process post data

Django use X-Requested-With to detect an ajax request, take a look of How django detect ajax request the sendData function is originated from Mozilla Docs Django use X-Requested-With to detect an ajax request, take a look of How django detect ajax request the sendData function is originated from Mozilla Docs

the following code made it happen:以下代码实现了它:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function sendData(){
    const XHR = new XMLHttpRequest();
    // Set up our request
    var csrftoken = getCookie('csrftoken');
    XHR.open("POST", "/order_pizza" );
    XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
    XHR.setRequestHeader('X-CSRFToken', csrftoken)
    // Bind the FormData object and the form element
    let FD = new FormData();
    // append the token
    FD.append('csrfmiddlewaretoken', csrftoken);

    let username = localStorage.getItem('username');
    FD.append('username', username);

    // The data sent is what the user provided in the form
    XHR.send(FD);
}

obviously we had to retrieve the csrf cookie first before we could use it as a form data.显然,我们必须先检索 csrf cookie,然后才能将其用作表单数据。

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

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