过去的一天,我一直在尝试向Ajax返回正确或错误的布尔值。
过程:有人提交的表单>发送到PHP文件>从PHP中,检查一切是否正确。如果是,则返回true和echo 'correct'
。 >输出结果。在这种情况下,它必须回显正确。并检查它是对还是错。
问题是,它将始终返回false。即使一切正确。因此,如我所料,当我的登录正确时,它将返回correct
。但这不会返回真。
我的表单:
<form id="loginform" class="col s12" name="loginform" method="post">
<div class="input-field col s12">
<i class="fas fa-user material-icons prefix"></i>
<input id="hn" type="text" class="validate" name="hn">
<label for="hn">Gebruikersnaam</label>
</div>
<div class="input-field col s12">
<i class="fas fa-key material-icons prefix"></i>
<input id="ww" type="password" class="validate" name="ww">
<label for="ww">Wachtwoord</label>
</div>
<button class="mui-btn mui-btn--raised mui-btn--primary" id="forminlog"><i class="fas fa-chevron-right"></i> Inloggen</button>
Ajax:
$("#forminlog").click(function(){
$.ajax({
type: 'POST',
data: {hn: document.getElementById("hn").value, ww: document.getElementById("ww").value},
url: 'login.php',
success: function(output) {
swal(output);
if(output == true){
alert("true");
} else {
alert("false");
}
}
});
event.preventDefault()
});
PHP:
<?php
function login(){
header('Content-Type', 'application/json');
//VARIABLEN
$pgebruiker = $_POST['hn'];
$pww = $_POST['ww'];
//LEGE VELDEN
if(empty($pgebruiker) || empty($pww)){
echo 'Vul alle velden in';
}
else {
//DATA VANUIT DB
include("connection.php");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT * FROM gebruikers WHERE gebruikersnaam = :gebruiker");
$pdoExec = $sth->execute(array(":gebruiker"=>$pgebruiker));
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
//GEBRUIKERSNAAM
$gebruikersnaam = $result->gebruikersnaam;
//WACHTWOORD
$wachtwoord = $result->wachtwoord;
if(!strcasecmp($pgebruiker, $gebruikersnaam) == 0){
echo 'Verkeerd gebruikersnaam.';
}
elseif(!password_verify($pww, $wachtwoord) /*strcasecmp($pww, $wachtwoord) == 0*/){
echo 'Verkeerd wachtwoord';
}
else{
echo 'Correcte gegevens.';
return true;
/*session_start();
$_SESSION['gebruiker'] = $gebruikersnaam;
header('Location: veilig.php');*/
//exit;
}
}
}
login();
?>
答案 0 :(得分:2)
您的login()
函数将返回两件事:
所以我建议您将数据作为json字符串输出,如下所示:
在login()
函数之前,声明一个数组:
$response = [];
然后,在所有条件下...只需相应地设置msg
和success
,例如,如果登录正确:
$response["msg"] = "You're logged in buddy!";
$response["success"] = true;
在所有条件的结尾echo
将该数组作为json字符串:
echo json_encode($response);
它将发送以下字符串:
{"msg":"You're logged in buddy!","success":true}
**确保echo
是该PHP文件中唯一的 echo
!
现在在客户端,在success
回调中,它将是:
success: function(output) {
// Parse the string.
var json = JSON.parse(output);
swal(json.msg); // Sweet Alert...
if(json.success){
// something to do with the boolean true
} else {
// Something else
}
}