如何将Ajax响应转换为纯文本字符串?我有一个全局变量,并将ajax响应存储到其中,但是当我将其与JavaScript字符串进行比较时,即使它们相等,它也会返回false。
这是我的代码:
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
myGlobalContainer.usn = response; //convert it to compare with string
$('#status').html(response);
}
});
}
}
在控制台中,当我输入数据库中已存在的用户名时,它会记录OK。这个OK存储在myGlobalContainer.usn中,但是当我像下面的代码进行比较时,它返回false。
if(myGlobalContainer.usn == "OK"){
return true;
}else{
return false;
}
我将添加 PHP 文件。
<?php
header("Content-Type: text/plain");
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if(isset($_POST['emp_username'])){
$usn = $_POST['emp_username'];
$checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0){
echo "OK";
}else{
echo "Your Username not exist";
}
exit();
}
if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
$pw = $_POST['emp_pw'];
$usn = $_POST['emp_usn'];
$get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $get_pw);
//$get_num_rows = mysqli_num_rows($query);
//echo $get_num_rows;
$row = mysqli_fetch_assoc($query);
//echo $row["emp_password"];
// check if password is match with username
if($pw == $row["emp_password"]){
echo "MATCH";
}else{
echo "Wrong password";
}
exit();
}
?>
Please help Thanks!
response
很可能已经是一个字符串了。问题可能是在你执行比较myGlobalContainer.usn == "OK"
的代码之前,在 Ajax 回调中设置了值。回调函数是异步执行的。 - Patrick Hundif(myGlobalContainer.usn == "OK")
代码在什么时候/地方确切地执行? - Phil