jQuery & AJAX login form

后端 未结 3 1957
清酒与你
清酒与你 2021-01-07 10:07

I am busy developing a site where I have a login box in the top right corner. I want the user to be able to log in on the same page, without refreshing.

OK, I got th

相关标签:
3条回答
  • 2021-01-07 10:48

    Just to elaborate on redsquare's answer, you would need to change your jQuery to this...:

    $(function() {
        /** 
            ...What ever else you might have onload... 
        **/
        $("a[name='logout']").live('click',function() {  // Now using the .live() event
            $.post("logout.php", function(data) {
                $("li.login").html(data);
                bind_login_submit();     // <---- Notice, this is new
            });
        });
        bind_login_submit();    // Call this function to initially bind the submit
    });
    
    function bind_login_submit() {
        $("form#login").unbind('submit').bind('submit',function() {
            var usernameVal = $("input[name='username']").val();
            var passwordVal = $("input[name='password']").val();
    
            $.post("login.php",{username : usernameVal, password : passwordVal}, function(data) {
                $("li.login").html(data);
            });
            return false;
        });
    }
    
    0 讨论(0)
  • 2021-01-07 10:53

    I don't really use jQuery, but my guess is that the post and click events aren't around anymore since it's been updated via ajax.

    You've got to add those events again.

    You could create an attach() function that selects the stuff you want and attaches the events and run it on callback of your request.

    0 讨论(0)
  • 2021-01-07 10:54

    Well you are replacing the html so you will lose the events you earlier bound to the removed elements. You can use the callback to rebind the events after you have replaced the html content. You can also look into the .live jQuery method however this will not work for the submit event so you will always have to rebind this after changing the form.

    0 讨论(0)
提交回复
热议问题