从 PHP 返回 http 响应代码到 AJAX

0 javascript php ajax

我正在尝试为网站制作登录页面。我有一个函数,它使用 AJAX 向 PHP 脚本发送请求以检查是否输入了正确的用户名和密码。如果查询返回成功结果,我发送 http_response_code(200),否则发送 http_response_code(403) . 但是,登录功能似乎没有返回任何响应状态。响应似乎未定义。在这种情况下,即使输入了正确的密码和用户名,该函数也会为我提供错误密码或用户名的窗口警报。我应该检查什么条件才能根据 http 响应代码确定成功函数应该做什么?是否有另一种方法可以根据 PHP 脚本的作用将条件返回给 AJAX?

这里是登录功能的代码。

function login(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var dataString = 'username1=' + username + '&password1=' + password;
if (username == '' || login == ''){
    window.alert("Please fill in username or password.");
}
else{
    $.ajax({
        type: "POST",
        url: "login.php",
        data: dataString,
        cache: false,
        crossDomain : true,
        success: function(response) {
            if (response.status == 200) {
                window.location = 'http://localhost/site.html';
            }
            else {
                window.alert("The password or username you have entered is not valid");
            }
        }
    });
}        
return false;
Run Code Online (Sandbox Code Playgroud)

}

这是我的 php 脚本。

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$password2 = $_POST['password1'];
$username2 = $_POST['username1'];
$connection = mysqli_connect("localhost", "root", "password", "database") or die("Unable to connect to MySQL");  
$query = mysqli_query($connection, "SELECT * FROM users where username = '$username2' AND password = '$password2'") or die(mysqli_error($connection));
$row = mysqli_fetch_array($query, MYSQLI_BOTH) or die(mysqli_error($connection));
if(!empty($row['username']) AND !empty($row['password'])) {
    session_start();
    $_SESSION['username'] = $username2;
    http_response_code(200);
    echo "Successful Login";
    exit;
}
else{
    http_response_code(403);
    echo "The password or username you have entered is not valid";
}
mysqli_close($connection);
?>
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 5

当您检查响应并发送 get 时 response.status您实际上并没有一个数组或对象作为您手中的响应:

因此,在检查登录名时,您可以使用status和 amessagejson_encode()它创建一个数组,以便您的 javascript 代码可以选择并读取它。

<?php
// fix your query connection - you are currently vulnerable. It does go outside of the scope of your question so I am not going to tackle it here.
if(!empty($row['username']) AND !empty($row['password'])) {
    session_start();
    $_SESSION['username'] = $username2;
    $return = array(
        'status' => 200,
        'message' => "Login Successful."
    );
    http_response_code(200);
}
else{
    $return = array(
        'status' => 403,
        'message' => "Login attempt denied."
    );
    http_response_code(403);
}
print_r(json_encode($return));
Run Code Online (Sandbox Code Playgroud)

现在您可以在 AJAX 函数中获取响应:

    success: function(response) {
        var data = $.parseJSON(response);
        if (data.status == 200) {
            window.location = 'http://localhost/site.html';
        }
        else {
            window.alert(data.message);
        }
    }
Run Code Online (Sandbox Code Playgroud)