Python 如何在 Django 中响应 ajax 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14642130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to response ajax request in Django
提问by CitooZz Banditozz
I have code like this:
我有这样的代码:
$(document).ready(function(){
$('#error').hide();
$('#submit').click(function(){
var name = $("#name").val();
if (name == "") {
$("#error").show("slow");
return false;
}
var pass = $("#password").val();
if (pass == "") {
$("#error").show("slow");
return false;
}
$.ajax({
url: "/ajax/",
type: "POST",
data: name,
cache:false,
success: function(resp){
alert ("resp");
}
});
});
});
and view in Django:
并在 Django 中查看:
def lat_ajax(request):
if request.POST and request.is_ajax:
name = request.POST.get('name')
return HttpResponse(name)
else :
return render_to_response('ajax_test.html',locals())
Where is my mistake? I'm a beginner in Django, please help me.
我的错误在哪里?我是 Django 的初学者,请帮助我。
回答by Lukasz Koziara
how about create dict and parse to json:
如何创建 dict 并解析为 json:
name = request.POST.get('name')
dict = {'name':name}
return HttpResponse(json.dumps(dict), content_type='application/json')
回答by luc
Put dataType: "json"in the jquery call. The resp will be a javascript object.
放入dataType: "json"jquery 调用。resp 将是一个 javascript 对象。
$.ajax({
url: "/ajax/",
type: "POST",
data: name,
cache:false,
dataType: "json",
success: function(resp){
alert ("resp: "+resp.name);
}
});
In Django, you must return a json-serialized dictionnary containing the data. The content_type must be application/json. In this case, the locals trick is not recommended because it is possible that some local variables can not be serialized in json. This wil raise an exception. Please also note that is_ajaxis a function and must be called. In your case it will always be true. I would also test request.methodrather than request.POST
在 Django 中,您必须返回一个包含数据的 json 序列化字典。content_type 必须是application/json. 在这种情况下,不推荐使用 locals 技巧,因为有可能在 json 中无法序列化某些局部变量。这将引发异常。另请注意,这is_ajax是一个函数,必须调用。在你的情况下,它永远是真的。我也会测试request.method而不是request.POST
import json
def lat_ajax(request):
if request.method == 'POST' and request.is_ajax():
name = request.POST.get('name')
return HttpResponse(json.dumps({'name': name}), content_type="application/json")
else :
return render_to_response('ajax_test.html', locals())
UPDATE : As mentioned by Jurudocs, csrf_token can also be a cause I would ecommend to read : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
更新:正如 Jurudocs 所提到的,csrf_token 也可能是我推荐阅读的原因:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
回答by catherine
$(document).ready(function(){
$('#error').hide();
$('#submit').click(function(){
var name = $("#name").val();
if (name == "") {
$("#error").show("slow");
return false;
}
var pass = $("#password").val();
if (pass == "") {
$("#error").show("slow");
return false;
}
$.ajax({
url: "/ajax/",
type: "POST",
data: {
'name': name,
'csrfmiddlewaretoken': '{{csrf_token}}'
},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
error: function(ts) {
alert(ts);
}
});
});
});
def lat_ajax(request):
if request.POST:
name = request.POST['name']
return HttpResponse(name)
else :
return render_to_response('ajax_test.html',locals())
回答by Sandeep Balagopal
if nothing works, put "@csrf_exempt" before your function
如果没有任何效果,请将“@csrf_exempt”放在您的函数之前
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def lat_ajax(request):
"""
your code
"""
回答by max
You have a typo:
你有一个错字:
success: function(resp){
alert ("resp");
}
should be
应该
success: function(resp){
alert (resp);
}
Also, regarding csrf, you must use the header like this:
此外,关于 csrf,您必须使用这样的标头:
$.ajax({
url: "some-url",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
回答by WesternGun
Just do this...(Django 1.11)
就这样做...(Django 1.11)
from django.http.response import JsonResponse
return JsonResponse({'success':False, 'errorMsg':errorMsg})
When you process the json part in jQuery, do:
在 jQuery 中处理 json 部分时,请执行以下操作:
$.ajax({
...
dataType: 'json',
success: function(returned, status, xhr) {
var result = returned['success']; // this will be translated into 'true' in JS, not 'True' as string
if (result) {
...
else {
...
}
}
});

