gpt4 book ai didi

python - 如何在 Django 中响应 ajax 请求

转载 作者:太空狗 更新时间:2023-10-29 22:02:24 25 4
gpt4 key购买 nike

我有这样的代码:

$(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");
}
});
});
});

并在 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())

我的错误在哪里?我是 Django 的初学者,请帮助我。

最佳答案

dataType: "json" 放入 jquery 调用中。 resp 将是一个 javascript 对象。

$.ajax({
url: "/ajax/",
type: "POST",
data: name,
cache:false,
dataType: "json",
success: function(resp){
alert ("resp: "+resp.name);
}
});

在 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())

更新:正如 Jurudocs 所提到的,csrf_token 也可能是我推荐阅读的原因:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

关于python - 如何在 Django 中响应 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14642130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com