When I try to POST with Javascript, Django's CSRF measures may get caught and fail, but the official document properly describes the measures. http://docs.djangoproject.jp/en/latest/ref/contrib/csrf.html?highlight=csrf#ajax
In addition, I uploaded a copy and paste to Github so that I can reuse it, so if you want to use it, please. https://github.com/juniskw/django_tools/blob/master/csrf_token_ajax.js
surprise.html
<head>
<script type="text/javascript" src="{{STATIC_URL}}js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/juniskw/django_tools/master/csrf_token_ajax.js"></script>
</head>
<body>
<h1>Let's Surprise!</h1>
<form id="surprise_fm" action="surprise/" method="post">
<input id="your_txt" type="text" name="your_txt">
<input id="surprise_btn" type="submit">
</form>
</body>
<script>
$(document).ready(function() {
$('#surprise_fm').submit(function() { //AJAX with the click of a button
$.ajax({
'url':$('form#surprise_fm').attr('action'),
'type':'POST',
'data':{
'your_txt':$('#your_txt').val(),
},
'dataType':'json',
'success':function(response){ //It is a process that works when communication is successful, and the returned response is included in the argument.
alert(response.your_surprise_txt); //Extract data from response and alert
},
});
return false;
});
});
</script>
urls.py
#...
url(r'^surprise/', 'views.for_ajax'),
#...
views.py
def for_view(req): #Function to display the view
return render(req,'surprise.html')
def for_ajax(req): #Functions that answer AJAX
import json
from django.http import HttpResponse,Http404
if req.method == 'POST':
txt = req.POST['your_txt'] #Get POST data
surprise_txt = txt + "!!!" #processing
response = json.dumps({'your_surprise_txt':surprise_txt,}) #Convert to JSON format ...
return HttpResponse(response,mimetype="text/javascript") #return. Is JSON treated as javascript?
else:
raise Http404 #GET request is treated as 404, but in reality it may not be necessary
If you rewrite a part of js as follows, you can just put ** csrf_token ** in the form.
$.ajax({
// ...
'data':$('form#surprise_fm').serialize(),
// ...
});
** serialize ** is probably a method that puts all the input elements in the form together in the form ** {name: value, ...} **. Django's ** csrf_token ** looks like a ** hidden type input element ** if you reveal the seeds, so this method could work like normal form processing.
Recommended Posts