无法读取null的属性“value”

时间:2013-07-19 16:46:54

标签: javascript jquery html ajax forms

我花了大概一个小时试图解决这个问题......无论我尝试什么,我都会收到这个错误:

Cannot read property 'value' of null

这是我的HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
  </head>
  <body>
    <h1>Hello, world!</h1>
    <div id="login_box"><form class="form-inline" action="JavaScript: login();" method="post">
  <input type="text" class="input-small" id="login_username" name="username" placeholder="Username">
  <input type="password" class="input-small" id="login_password" name="password" placeholder="Password">
  <label class="checkbox"><input type="checkbox" id="login_autologin" name="autologin"> Remember me  </label>
  <button type="submit" class="btn" name="login">Sign in</button>
</form></div>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/overall_js.js"></script>
  </body>
</html>

和相关的JS文件(overall_js.js):

function login() {
$("#login_box").html("logging you in....");
console.log(document.getElementById("login_username").value);
$.post("user.php?mode=login", {
    username : document.getElementById("login_username").value, 
    password : document.getElementById("login_password").value,
    autologin : document.getElementById("login_autologin").value,
}).done(function(data) {
    result = JSON.parse(data);
    if (result.status == 3) {
        $("#login_box").html(
                "Welcome back, " + result.user_row.username + "!");
    } else {
        $("#login_box")
                .html("You was not logged in: , " + result.error_msg);
    }
});
}

谢谢你能搞清楚这一点!我也是jQuery和JS的新手,所以如果有人有任何建议让它更“标准”,任何提示都会受到赞赏!

2 个答案:

答案 0 :(得分:6)

这一行

$("#login_box").html("logging you in....");

替换<div>的内容。您删除表单和所有输入元素...

答案 1 :(得分:1)

见下面第6和第7行所需的更正:

function login() {
    $("#login_box").append("logging you in....");
    var u = $('#login_username').val();
    var p = $('#login_password').val();
    var al = $('#login_autologin').is(':checked');
    console.log(u, p, al);
    $.post("user.php?mode=login", {
        username : u, 
        password : p,
        autologin : al,
    }).done(function(data) {
        result = JSON.parse(data);
        if (result.status == 3) {
            $("#login_box").html(
                    "Welcome back, " + result.user_row.username + "!");
        } else {
            $("#login_box")
                    .html("You was not logged in: , " + result.error_msg);
        }
    });
}