在Ajax php和mysql中读取响应

Reading a response in Ajax php and mysql

本文关键字:读取 响应 mysql Ajax php      更新时间:2023-09-26

我无法让代码工作并重定向到2个不同的页面,这取决于信息是否正确。。。

到目前为止,我的登录页面上有这个:

$(function () {
$('#form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'newfile.php',
        data: $('#form').serialize(),
        success: function (response){
        alert(response); 
                    if (success.text="Username or Password incorrect")
                        window.location.href = "index.php"; 
                    else if (success.text="login successful") {
                        window.location.href = "login_success.html";
                    } else {  
                    }
            }
        })
})

并且Im从中读取的信息是(从另一页):

<?php    
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
     die(" Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$sql="SELECT myusername, mypassword FROM user WHERE myusername = '" . mysqli_real_escape_string($conn, $myusername) . "' and mypassword = '" . mysqli_real_escape_string($conn, $mypassword) . "';";
$result = $conn->query($sql);
if ($result->num_rows >0) {
    echo "login successful";
} else {
    echo "Username or Password incorrect";
}
$conn->close();
?> 

我希望这对你有用,试试这个:

if (response=="usernames or Password incorrect") {
    window.location.href = "index.php";
} 
else if (response=="login successful") 
{
    window.location.href = "login_success.html";
 } 
else { }

在ajax成功中使用此代码。实际上,您在PHP中使用了简单的ECHO,在ajax中成功地使用了response.text。

更新:

您使用=符号进行比较,应该使用==运算符进行比较

更新2:

我建议在php中使用status as true false not long字符串,如:

if ($result->num_rows >0) {
    echo true;
} else {
    echo false;
}

Than在ajax响应中:

if(response == true){
// Success url
}
else {
// failure url
}

变量success将在success回调函数中未定义。因此不会执行下一行。因此页面不会被重定向。根据您的php代码,您需要检查响应是否等于not的相应结果。