首页 > 解决方案 > jQuery AJAX 登录问题(JSON 解析失败)

问题描述

我的 jQuery AJAX 登录有问题。当我尝试登录控制台时,会弹出一条消息“请求的 JSON 解析失败。 ”。代码的主要目的是登录到受简单 jQuery 幻灯片验证码保护的管理仪表板,因为我不喜欢 reCAPTCHA。那是我的 jQuery AJAX 调用:

$(".slidercaptcha").hide();
    $( "#login" ).on( "submit", function( event ) {
        event.preventDefault();
        $(".beforeContinue").hide();
        $(".slidercaptcha").fadeIn('fast');
    });
    var Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 4000
    });
    var captcha = sliderCaptcha({
        id: 'captcha',
        repeatIcon: 'fa fa-redo',
        onSuccess: function() {
            $.ajax({
                url: 'ajax_requests/login_ajax.php',
                type: 'POST',
                cache: false,
                data: {
                    'username': $('#username').val(),
                    'password': $('#password').val()
                },
                contentType: "application/json",
                dataType: 'JSON',
                success: function(response) {

                    Toast.fire({
                        icon: 'success',
                        title: "Successfully logged in! Redirecting..."
                    });

                    setTimeout(function() {

                        if (response.status == "1") {

                            location.href = "index.php";

                        } else if (response.status == "2") {

                            location.href = "index.php";

                        } else {

                            Toast.fire({
                                icon: 'error',
                                title: "Something went wrong, please try again later!"
                            });

                        }

                    }, 2000);
                },
                error: function(jqXHR, exception) {
                    var msg = '';
                    if (jqXHR.status === 0) {
                        msg = 'Not connect.\n Verify Network.';
                    } else if (jqXHR.status == 404) {
                        msg = 'Requested page not found. [404]';
                    } else if (jqXHR.status == 500) {
                        msg = 'Internal Server Error [500].';
                    } else if (exception === 'parsererror') {
                        msg = 'Requested JSON parse failed.';
                    } else if (exception === 'timeout') {
                        msg = 'Time out error.';
                    } else if (exception === 'abort') {
                        msg = 'Ajax request aborted.';
                    } else {
                        msg = 'Uncaught Error.\n' + jqXHR.responseText;
                    }
                    console.log(msg);
                }
            });
        }
    });

这就是我的 PHP 表单(login_ajax.php):

<?php header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","shopperapproved");

$username = $conn->real_escape_string($_POST['username']);
$password = $conn->real_escape_string($_POST['password']);
$password_crypted = hash('sha256', $conn->real_escape_string($password));

$_login = $conn->prepare("SELECT * FROM `admin_users` WHERE `username`=? AND `password`=?");
$_login->bind_param("ss", $username, $password_crypted);
$_login->execute();
if ($_login->num_rows > 0) {
$_SESSION['login_session'] = hash('sha256', rand(6453, 891673));
if (isset($_SESSION['login_session'])) {
    $result = array("status" => "1");
    echo json_encode($result);
} else {
    $result = array("status" => "0");
    echo json_encode($result);
}
} else {
$result = array("status" => "0");
echo json_encode($result);
}
$_login->close();
?>

提前致谢。

标签: jqueryjsonajaxcaptcha

解决方案


如果你做了什么,你会得到什么:

$res = json_encode($result);
print_r($res)
echo json_encode($result);

还要检查您的 ajax 调用:

success: function(response) {
   var data = JSON.parse(response);
   console.log(data)
... your code
}

我认为你的 json 字符串是不正确的。

我在你的代码中看到:

if ($_login->execute()) {

所以什么都不会被执行
示例:

$_login->execute();

$result = $_login->get_result();
$user   = $result->fetch_array(MYSQLI_ASSOC);

if ($user !== false) {
  $json = json_encode($user);
  print_r($json); // You should get back and Json String.
} else {
  // there where no results
}

推荐阅读