使用 $.post 对用户进行身份验证以返回自定义错误/成功消息

Using $.post to authenticate user to return custom error / success message

本文关键字:自定义 返回 错误 消息 成功 身份验证 post 用户 使用      更新时间:2023-09-26

我有这个jQuery来验证用户进入站点,我如何对登录返回的成功/错误进行两个操作.php?是否可以在成功时刷新页面(例如)并在登录信息未成功时发布错误消息.php。我希望我的问题很清楚。这是代码。现在它只是粘贴登录的数据输出.php我不知道如何分离返回服务器端的成功/错误。

$("#form-login").submit(function(event) {
    event.preventDefault();
    var $form = $( this ),
        log = $form.find( 'input[name="log"]' ).val(),
        pwd = $form.find( 'input[name="pwd"]' ).val(),
        rememberme = $form.find( 'input[name="rememberme"]' ).val();
    $.post( '/ajax/login.php', { log: log, pwd: pwd, rememberme: rememberme },
        function(data) {
            $(".form-login-status").html(data);
        }
    );
});

在服务器端脚本中,返回状态和消息,如下所示:

$result = array();
if (login_is_successful()) {
    $result['status'] = true;
    $result['message'] = "Logged in";
} else {
    $result['status'] = false;
    $result['message'] = 'Incorrect password';
}
echo json_encode($result);

这使您可以灵活地从服务器端发送任何响应消息,而无需在客户端代码中专门处理它。明天,如果您想分别发送消息"用户名不正确"和"密码不正确",只要$result['status']保持false,您就可以在不对 JS 进行任何更改的情况下执行此操作。

然后在$.post的成功处理程序中,执行以下操作:

success : function(resp) {
    if (resp.status) {
        //user logged in
        //refresh page
        window.location.reload();
    } else {
        //failed authentication
        alert(resp.message);
    }
}

确保设置dataType: 'json'

重要提示:

如果身份验证失败,将不会调用$.post中的 erorr 处理程序,因此您必须在成功处理程序中检查失败的身份验证。

仅当发出 POST 请求时出错时,才会调用错误处理程序。

当然,它在文档中:

$.post("example.php", {},  function() {
      alert("success");
    })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

在"成功"处理程序中,您需要处理请求的 URI 返回的标志,该标志说明凭据是否对用户进行身份验证。您需要基于该逻辑对逻辑进行分支。