Ajax和Django render_to_response(如何呈现成功函数内的响应)

时间:2012-07-20 01:28:39

标签: ajax django

目前我正在尝试实施登录验证系统。我正在使用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)

P.S。目前我正在使用虚拟模板和HttpResponse将数据发送到ajax成功回调函数。有没有更有效的方法来实现这一点(发送回json数据)?我会等你的回复!

1 个答案:

答案 0 :(得分:4)

from django.contrib.auth import authenticate, login as auth_login

def login(request):

    # Use authentication framework to check user's credentials
    # http://djangosnippets.org/snippets/1001/ for auth backend
    user = authenticate(
               email    = request.POST['email'],
               password = request.POST['password'], )

    if user is not None:
        # Use Auth framework to login user
        auth_login(request, user)
        return render_to_response('profile.html',
                 context_instance=RequestContext(request))

    else:
        # Return Access Denied
        # Never return bad email/bad password. This is information leakage
        # and helps hackers determine who uses your platform and their emails.
        return HttpResponse("Failed: Bad username or password", status=403)


function loginSubmit(email, password) {
    $.ajax({
        url: "/login",
        type: "POST",
        data: {email:email, password:password},
        success: function(data) {
            var returned_html = $(data);
            $("#target_profile_area").clear().append(returned_html);
        },
        error: function(jqXHR) {
            if (jqXHR.statusCode == 403) {
                $("#loginMessage").text("Your login details are incorrect");
            } else {
                $("#loginMessage").text("Error Contacting Server");
            }
            $("#loginError").show();
            $("#loginError").fadeOut(5000, function() {});
        }
    });
}