Jquery and Django CSRF Token

前端 未结 3 899
礼貌的吻别
礼貌的吻别 2020-12-04 22:16

I have 2 html Pages.

A Parent Page and a Child Page. The Child Page Contains a Submit Button that runs code on the Parent Page to submit an Ajax message.

I

3条回答
  •  眼角桃花
    2020-12-04 22:41

    If you are sending a POST request body it maybe easier to add the csrf token as a request header instead. I find this approach easier to read, as it does not clutter up the request body with a token. Most AJAX request will send the csrf token as a header as suggested by the Django documentation.

    function startTest(testId) {
      var payload = JSON.stringify({
        test_id : testId
      });
      $.ajax({
        url: "/test-service/",
        method: "POST",
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
        data: payload,
        dataType: "json"
      }).done(function(response) {
        console.log(response.id + " " + response.name);
      }).fail(function (error) {
          console.log(error);
      });
    }
    

提交回复
热议问题