开发者

Ajax to login users...callback function not working

This is my second foray into Ajax and I'm not quite sure how to pull this off.

So I have a modal window that opens when an anonymous user attempts to perform a certain task. The window contains a user signup form that I then $.post to my Django login view. If username/password are valid, user is logged in an status code of 1 is returned as the response. IF not, a status of 0 is returned.

When I try to do it outside of js, it works. However, within my script, it fails. I think that it has to do with the response content_type and how I'm interpreting it. I'm not sure.

def login_async(request):       
if request.method=='POST' and len(request.POST['username'])<20 and len(request.POST['password'])<20:
    username=request.POST.get('username', '') #probably need to script tags here
    password=request.POST.get('password', '')
    user=auth.authenticate(username=username, password=password)
    if user is not None:
        auth.login(request,user)
        status开发者_Python百科=1
        response=HttpResponse()
        response['Content_Type']="text/html"
        response.write(status)
        return response
    else:
        status=0
        response=HttpResponse()
        response['Content_Type']="text/html"
        response.write(status)
        return response




$('input#login').click(function(event){
    $.post("/login_async/", {username:$('input[name=username]').val(), password:$('input[name=password]').val()}, //could also use $(this).serialize() here to capture all form inputs
        function(data){
            if(data==1){
                $('#login').dialog("close");
                }
    });
    });

What's the problem here? I initially tried to return the response as JSON but I couldn't figure out how to make serialize.serializers("json",status) work. I kept getting an error.

One last question...

If I get a valid status (user is signed in), that will influence the behavior of modal windows on the page. The modal windows open based on logged in status. If a user is signed in, one set of windows open on a click event, and vice versa. This toggle is dependent on Django context {% user.is_authenticated %}.

That context renders only once right, on page load? Can I do anything to communicate the status change to the modal windows that's secure from easy hacks?


It should be Content-Type. If that doesn't fix your problem, try adding a dataType parameter at the end of the $.post call.

$.post("/login_async/", {}, function(data){
  // fancy stuff
}, "html");


Yeah I thought it over more and realized that I should just unbind the existing click event handlers on the modal windows and then bind new event handlers depending on the ajax response.

I love programming

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜