mirror of https://github.com/django/django.git
Rewrote CSRF JavaScript example without jQuery.
This commit is contained in:
parent
9736137cdc
commit
3fe5d0128b
|
@ -137,39 +137,29 @@ and read the token from the DOM with JavaScript:
|
||||||
|
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<script>
|
<script>
|
||||||
// using jQuery
|
var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
|
||||||
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
Setting the token on the AJAX request
|
Setting the token on the AJAX request
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
Finally, you'll have to actually set the header on your AJAX request, while
|
Finally, you'll need to set the header on your AJAX request. Using the
|
||||||
protecting the CSRF token from being sent to other domains using
|
`fetch()`_ API:
|
||||||
`settings.crossDomain <https://api.jquery.com/jQuery.ajax/>`_ in jQuery 1.5.1
|
|
||||||
and newer:
|
|
||||||
|
|
||||||
.. code-block:: javascript
|
.. code-block:: javascript
|
||||||
|
|
||||||
function csrfSafeMethod(method) {
|
var request = new Request(
|
||||||
// these HTTP methods do not require CSRF protection
|
/* URL */,
|
||||||
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
|
{headers: {'X-CSRFToken': csrftoken}}
|
||||||
}
|
);
|
||||||
$.ajaxSetup({
|
fetch(request, {
|
||||||
beforeSend: function(xhr, settings) {
|
method: 'POST',
|
||||||
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
|
mode: 'same-origin' // Do not send CSRF token to another domain.
|
||||||
xhr.setRequestHeader("X-CSRFToken", csrftoken);
|
}).then(function(response) {
|
||||||
}
|
// ...
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
If you're using AngularJS 1.1.3 and newer, it's sufficient to configure the
|
.. _fetch(): https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
|
||||||
``$http`` provider with the cookie and header names:
|
|
||||||
|
|
||||||
.. code-block:: javascript
|
|
||||||
|
|
||||||
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
|
|
||||||
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
|
|
||||||
|
|
||||||
Using CSRF in Jinja2 templates
|
Using CSRF in Jinja2 templates
|
||||||
------------------------------
|
------------------------------
|
||||||
|
|
Loading…
Reference in New Issue