我在我的网站中构建了一个登录功能,用户需要启动引导程序模式才能登录。但是,当用户输入了错误的名称或密码时,它将指示其他页面显示错误消息。我想在模式中显示错误消息,而不是转到其他页面。我已经看到了一些使用ajax的示例。但是,我是jquery的新手,我不知道执行ajax登录验证应包含什么内容。
//模态
<div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content bg-light">
<div class="modal-header bg-dark">
<h4 class="col-12 text-center text-white comp ">Sign in</h4>
</div>
<div class="modal-body mx-3">
<form action="authentication.php" method="post">
<div class="md-form mb-5">
<i class="fas fa-envelope prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
email">Username:</label>
<input type="text" name="username" class="form-control validate">
</div>
<div class="md-form mb-4">
<i class="fas fa-lock prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
pass">Password:</label>
<input type="password" name="password" class="form-control validate">
</div>
<form>
</div>
<div class="modal-footer d-flex justify-content-center bg-primary">
<button type="submit" class="btn btn-default text-white
comp">Login</button>
</div>
</div>
</div>
</div>
// php
<?php
session_start()
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'test';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and
display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());}
// Now we check if the data from the login form was submitted, isset()
will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Please fill both the username and password field!');}
// Prepare our SQL, preparing the SQL statement will prevent SQL
injection.
if ($stmt = $con->prepare('SELECT id, password FROM player WHERE name =
?')) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case
the username is a string so we use "s"
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
// Store the result so we can check if the account exists in the
database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to
store the hashed passwords.
if ($_POST['password'] === $password) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they
basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
}
\ js(仅概念)
function login(){
if(validationLogin()){
$.ajax({
url: "authentication.php",
type: "POST",
data: {"username": user,
"password": password,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "OK"){
window.location.href = "home.php",
}else{
window.location.href = "squad.php",
}
}
});
}else{
alert("Incorrect data");
}}
我想让错误消息在表单中内联显示。感谢您的帮助。
<a href="" class="btn btn-secondary btn-rounded login" data-
toggle="modal"
data-target="#modalLoginForm">Login</a>
<div class="login-container"></div>
// js
$('a.login').click(function(event) {
var url = "userlogin.php";
$('.login-container').load(url,function(result){
$('#modalLoginForm').modal({show:true});
});
});
//新的php文件
<script type="text/javascript">
$('#loginForm').on('submit', function( event ) {
// prevent the default submit
event.preventDefault();
var form = $(this);
$.ajax({
url: "authentication.php",
type: "POST",
// use the forms data
data: form.serialize(),
beforeSend: function() {
console.log( "Processing..." );
},
success: function( response ){
// do sth with the response
if(response == "OK") {
// credentials verified
// redirect
location.reload();
}else{
// credentials incorrect
// append errormessage to modal
form.closest('.modal-body').append('<div class="error text-
danger">*'+response+'</div>');
}
},
error: function( response ) {
console.log(response);
}
});
return false;
});
</script>
<div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content bg-light">
<div class="modal-header bg-dark">
<h4 class="col-12 text-center text-white comp ">Sign in</h4>
</div>
<div class="modal-body mx-3">
<form action="authentication.php" method="post">
<div class="md-form mb-5">
<i class="fas fa-envelope prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
email">Username:</label>
<input type="text" name="username" class="form-control validate">
</div>
<div class="md-form mb-4">
<i class="fas fa-lock prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
pass">Password:</label>
<input type="password" name="password" class="form-control validate">
</div>
<form>
</div>
<div class="modal-footer d-flex justify-content-center bg-primary">
<button type="submit" class="btn btn-default text-white
comp">Login</button>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
使用ajax拦截表单提交的默认行为,您将走上正确的道路。首先,您需要在网站上实现jQuery,以便可以使用ajax。
在那之后,您需要拦截提交中的默认值:
// give your form an id
<form id="loginForm" ... > ...
拦截提交:
$('#loginForm').on('submit', function( event ) {
// prevent the default submit
event.preventDefault();
var form = $(this);
$.ajax({
url: "authentication.php",
type: "POST",
// use the forms data
data: form.serialize(),
beforeSend: function() {
console.log( "Processing..." );
},
success: function( response ){
// do sth with the response
if(response === "OK") {
// credentials verified
// redirect
}else{
// credentials incorrect
// append errormessage to modal
form.closest('.modal-body').append('<div class="error">'+response+'</div>');
}
},
error: function( response ) {
console.log(response);
}
});
});
成功回调中的响应将使您获得php脚本的输出内容,例如echo "OK";
(如果凭据正确且会话已启动)。在其他所有情况下,响应都将附加到您的模态主体上。
顺便说一句。您永远不应将密码以纯文本格式存储在数据库中。始终使用某种哈希来存储它们!