我是PHP的初学者。 我的代码
<?php
session_start();
$username = "ADMIN";
$host = "localhost";
$password = "chmuhammadsohaib123";
$database = "USER";
$con = mysqli_connect($host, $username, $password, $database);
$USERNAME = $_POST["lusername"];
$PASSWORD = $_POST["lpassword"];
if (isset($_POST["login"])) {
if (isset($_POST["loggedin"])) {
setcookie("RAUSERNAME", $USERNAME);
setcookie("RAPASSWORD", $PASSWORD);
}
$_SESSION["SRAUSERNAME"] = $USERNAME;
$_SESSION["SRAPASSWORD"] = $PASSWORD;
}
if (isset($_POST["login"])) {
$data = mysqli_query($con, "SELECT * FROM `INFO` WHERE `USERNAME` = '$USERNAME'");
if (mysqli_num_rows($data)>0) {
echo "<script type='text/javascript'>window.location.replace('../');</script>";
}
else {
print("<script type='text/javascript'>document.getElementsByClassName('errors').innerHTML = '<h1 class='redback'>SORRY, BUT THIS ACCOUNT DOESN'T EXISTS</h1>';</script>");
}
}
?>
MY HTML PAGE
<body>
<div class="errors"></div>
<fieldset class="replacement">
<legend>LOGIN</legend>
<h1>LOGIN WITH YOUR INFORMATION</h1><br><br>
<form method="POST" action="<?php $_SERVER["php_self"]; ?>">
<input type="text" name="lusername" placeholder="YOUR USERNAME">
<input type="password" name="lpassword" placeholder="YOUR PASSWORD" class="password">
<br>
<br>
<label>KEEP ME LOGGED IN: </label>
<input type="checkbox" name="loggedin" checked>
<br><br>
<input type="submit" name="login" value="LOGIN"></form>
</fieldset>
</div>
</body>
</html>
如上所述,当我更改 错误 的innerHTML时,它不会发生变化。它表示控制台中缺少 ; ,有时 错误 null 。我该如何解决?
答案 0 :(得分:2)
在您回显javascript代码时,dom中不存在标识为errors
的html元素。因此,getElementById
的返回将始终未定义。
<script>document.getElementById("errors")...</script>
... some more html
<div id="errors"></div>
您可以通过在 dom文档准备好之后调用javascript代码来解决此问题。使用jQuery,你可以这样做
// event handler for document ready
$(function() {
// at this point, the dom is ready and the 'errors' id exists
$('#errors').html("some error message");
});
这可行,但似乎有点不必要。更好的方法是使用php回显实际的错误消息,不要使用javascript来执行此操作。
$error = false;
if (mysqli_num_rows($data)>0) {
header('location: ../');
} else {
$error = '<h1 class="redback">SORRY, BUT THIS ACCOUNT DOESN\'T EXISTS</h1>';
}
以后
<div class="errors">
<?php if ($error) echo $error; ?>
</div>