3
目前我正在尝试实现登录验证系统。我正在使用ajax,以便用户可以在不被重定向到其他页面的情况下获得响应。我的ajax函数发送用户输入的电子邮件和密码,并在回调函数中获取消息,可以有三种类型:电子邮件,密码或实际的HttpResponse对象。但我不知道如何使用ajax和jQuery来渲染给定的http响应对象。 location.href是一个选项吗?我正在粘贴下面的代码。Ajax和Django render_to_response(如何呈现成功函数内的响应)
在javascript中:
function loginSubmit(email, password) {
var d= "email=" + email + "&password=" + password;
$.ajax({
url: "/login",
type: "POST",
dataType: "text",
data: d,
success: function(m) {
if (m == "email") {
$("#emailMessage").html("There is no account associated with this email address.");
$("#emailError").show();
$("#emailError").fadeOut(5000, function() {});
} else if (m == "password") {
$("#emailMessage").html("There is no account associated with this email address.");
$("#emailError").show();
$("#emailError").fadeOut(5000, function() {});
} else {
}
}
});
}
鉴于功能:
def login(request):
json = request.POST
e = json['email']
p = json['password']
u = User.objects.filter(email=e)
if (len(u)):
up = User.objects.filter(email=e, password=p)
if (len(up)):
return render_to_response('profile.html', context_instance=RequestContext(request))
else:
data = "password"
c = RequestContext(request, {'result':data})
t = Template("{{result}}")
datatype=u"application/javascript"
return HttpResponse(t.render(c), datatype)
else:
data = "email"
c = RequestContext(request, {'result':data})
t = Template("{{result}}")
datatype=u"application/javascript"
return HttpResponse(t.render(c), datatype)
P.S.目前,我正在使用虚拟模板和HttpResponse将数据发送到ajax成功回调函数。有没有更有效的方法来完成这个(发回json数据)?我会等待你的回复家伙!