1.前端Ajax代码(修改前)
<script>
$(function(){
$('input:button').click(function(){
var username = $('input[name="username"]').val()
var password = $('input[name="password"]').val()
$.ajax({
url: "{% url 'api:books' %}",
type: 'post',
dataType: 'json',
data: JSON.stringify({'username': username, 'password': password}),
headers: {'X-CSRFToken': "{{ csrf_token }}"},
success:function(data){
if(data.res=='ok'){
location.href = '{% url "ajax:index" %}'
}
}
})
})
})
</script>
2.后端代码(修改前)
import json
def login(request):
data = json.loads(request.body)
return JsonResponse({'res': 'ok'})
3.报错输出
4.前端Ajax代码(修改后)
<script>
$(function(){
$('input:button').click(function(){
var username = $('input[name="username"]').val()
var password = $('input[name="password"]').val()
$.ajax({
url: "{% url 'api:books' %}",
type: 'post',
dataType: 'json',
data: {'username': username, 'password': password},
headers: {'X-CSRFToken': "{{ csrf_token }}"},
success:function(data){
if(data.res=='ok'){
location.href = '{% url "ajax:index" %}'
}
}
})
})
})
</script>
5.后端代码(修改后)
def login(self, request):
username = request.POST.get('username')
password = request.POST.get('password')
return JsonResponse({'res': 'ok'})