Fixed #15284 - improved example jQuery code for adding X-CSRF-Token
Using the ajaxSend event is better than beforeSend, because the beforeSend callback can have only one value, which makes it painful if it is needed by multiple bits of javascript. Thanks to LukeMaurer for report and initial patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@15515 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
ee06020240
commit
d068a04244
|
@ -90,12 +90,11 @@ every POST request. For this reason, there is an alternative method: on each
|
|||
XMLHttpRequest, set a custom `X-CSRFToken` header to the value of the CSRF
|
||||
token. This is often easier, because many javascript frameworks provide hooks
|
||||
that allow headers to be set on every request. In jQuery, you can use the
|
||||
``beforeSend`` hook as follows:
|
||||
``ajaxSend`` event as follows:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
$.ajaxSetup({
|
||||
beforeSend: function(xhr, settings) {
|
||||
$('html').ajaxSend(function(event, xhr, settings) {
|
||||
function getCookie(name) {
|
||||
var cookieValue = null;
|
||||
if (document.cookie && document.cookie != '') {
|
||||
|
@ -115,7 +114,6 @@ that allow headers to be set on every request. In jQuery, you can use the
|
|||
// Only send the token to relative URLs i.e. locally.
|
||||
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Adding this to a javascript file that is included on your site will ensure that
|
||||
|
|
Loading…
Reference in New Issue