代码之家  ›  专栏  ›  技术社区  ›  Starx

如何将HTTP认证与jquery通信来认证登录系统?

  •  0
  • Starx  · 技术社区  · 16 年前

    你知道怎么做吗?也请包括例子

    2 回复  |  直到 16 年前
        1
  •  1
  •   mario    16 年前

    (令我惊讶的是)jQuery内置了 support 用于提供HTTP身份验证凭据:

    $.ajax({
        url: "http://example.org/",
        username: "NAMENAMENAMENAMENAME",
        password: "PWPWPWPWPWPWPWPWPWPW",
        ...
    })
    

    或者可以覆盖XMLHttpRequest对象,如本例所示: http://dothow.blogspot.com/2009/05/http-basic-authentication-with-jquery.html

        2
  •  1
  •   Matt user129975    16 年前

    基本HTML:

    <form id="login-form" action="/login.php" method="post">
        <label for="username">Username: </label> 
        <input type="text" name="username" id="username"/><br />
    
        <label for="Password">Password: </label> 
        <input type="text" name="password" id="password"/><br />
    
        <input type="submit" value="Login"/>
    </form>​
    

    基本jQuery:

    $(document).ready(function() {
        $('#login-form').bind('submit', function (e) {
            var self = $(this);
    
            // See ajax: http://api.jquery.com/jQuery.post
            // See serialize: http://api.jquery.com/serialize()
            jQuery.post(self.attr('action'), self.serialize(), function () {
                if (response.success) {
                    // wooo, logged in
                } else {
                    alert("Invalid username or password. Please try again");
                }
            }, 'json');
    
            e.preventDefault(); //prevent the form being posted 
        });
    });​
    

    基本PHP:

    <?php
    if ($_POST['username'] == 'Admin' && $_POST['password'] == 'letmein') {
        echo json_encode(array('success' => true));
    } else {
        echo json_encode(array('success' => false));
    };
    ?>