繁体   English   中英

在Ajax php和mysql中读取响应

[英]Reading a response in Ajax php and mysql

我无法使代码正常工作并重定向到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 {  
                    }
            }
        })
})

我从中读取的信息是(从另一页):

<?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作为true false不是长字符串,例如:

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

比在ajax中的响应:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM