@@ -39,6 +39,34 @@ replaced instead of using ``CsrfMiddleware``.
3939 (previous versions of Django did not provide these two components
4040 of ``CsrfMiddleware`` as described above)
4141
42+ AJAX
43+ ----
44+
45+ While the above method can be used with AJAX POST requests, it has some
46+ inconveniences: you have to remember to get the CSRF token from the HTML
47+ document and pass it in as POST data with every POST request. For this reason,
48+ there is an alternative method: on each XMLHttpRequest, set a custom
49+ `X-CSRFToken` header to the value of the CSRF token. This is often easier,
50+ because many javascript frameworks provide hooks that allow headers to be set on
51+ every request. In jQuery, you can use the ``beforeSend`` hook as follows:
52+
53+ .. code-block:: javascript
54+
55+ $.ajaxSetup({
56+ beforeSend: function(xhr, settings) {
57+ if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
58+ // Only send the token to relative URLs i.e. locally.
59+ xhr.setRequestHeader("X-CSRFToken",
60+ $("#csrfmiddlewaretoken").val());
61+ }
62+ }
63+ });
64+
65+ Adding this to a javascript file that is included on your site will ensure that
66+ AJAX POST requests that are made via jQuery will not be caught by the CSRF
67+ protection. This will only work if you remember to include a form on the page,
68+ so that the input with id 'csrfmiddlewaretoken' will be found.
69+
4270Exceptions
4371----------
4472
@@ -61,10 +89,6 @@ disable the view protection mechanism (``CsrfViewMiddleware``) and the
6189response post-processing (``CsrfResponseMiddleware``) respectively.
6290They can be used individually if required.
6391
64- You don't have to worry about doing this for most AJAX views. Any
65- request sent with "X-Requested-With: XMLHttpRequest" is automatically
66- exempt. (See the next section.)
67-
6892How it works
6993============
7094
@@ -98,14 +122,6 @@ The Content-Type is checked before modifying the response, and only
98122pages that are served as 'text/html' or 'application/xml+xhtml'
99123are modified.
100124
101- The middleware tries to be smart about requests that come in via AJAX. Many
102- JavaScript toolkits send an "X-Requested-With: XMLHttpRequest" HTTP header;
103- these requests are detected and automatically *not* handled by this middleware.
104- We can do this safely because, in the context of a browser, the header can only
105- be added by using ``XMLHttpRequest``, and browsers already implement a
106- same-domain policy for ``XMLHttpRequest``. (Note that this is not secure if you
107- don't trust content within the same domain or subdomains.)
108-
109125
110126.. _9.1.1 Safe Methods, HTTP 1.1, RFC 2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
111127
0 commit comments