目前我正在尝试实现一个登录验证系统。我使用ajax,这样用户可以在不被重定向到另一页的情况下得到响应。我的ajax函数发送用户输入的电子邮件和密码,并在回调函数中获取消息,这些消息可以是三种类型之一:电子邮件、密码或实际的HttpResponse对象。但是我不知道如何使用ajax和jquery渲染给定的http响应对象。是location.href一个选择?我在下面粘贴代码。
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)
附言:目前我正在使用一个虚拟模板和HttpResponse将数据发送到ajax成功回调函数。有没有更有效的方法来完成这个任务(发送json数据)? 我会等待大家的回复!
注:此处保留了HTML标签。