You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter中显示SweetAlert登录拒绝提示消息?

问题分析与修复方案

看起来你的问题出在**do_login()方法的逻辑顺序错误**,以及潜在的PHP错误导致AJAX无法接收到预期的JSON响应,从而让错误提示无法正常显示。让我们一步步拆解并修复:

核心问题:提前访问不存在的$user属性

在你的do_login()方法里,你在判断$user是否存在之前,就尝试获取$user->id来创建$userdata数组:

$user = $this->admin->fetch('admin', $data)[0];
$userdata = array('a_logged_in' => TRUE, 'adminid' => $user->id); // 这里会直接报错!
if (!$user) {
    // 这段代码永远执行不到,因为上面已经抛出PHP错误了
}

当用户输入错误的账号密码时,$user是不存在的对象/空值,此时访问$user->id会触发**"Trying to get property 'id' of non-object"**的PHP错误,导致整个请求返回500状态码,AJAX无法收到正确的JSON响应,自然也就无法触发SweetAlert提示。

修复步骤

1. 调整逻辑顺序,先判断$user是否存在

把$userdata的创建移到$user存在的分支里,避免提前访问不存在的属性:

public function do_login() { 
    $username = $this->input->post('username', TRUE); 
    $password = $this->input->post('password', TRUE); 
    $this->form_validation->set_rules('username', 'Username', 'required|xss_clean|trim'); 
    $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|trim'); 
    $validator = array('success' => FALSE, 'messages' => array()); 
    if ($this->form_validation->run() == TRUE) { 
        $data = array('username' => $username, 'password' => sha1($password)); 
        $user_list = $this->admin->fetch('admin', $data);
        $user = !empty($user_list) ? $user_list[0] : null;

        // 先判断用户是否存在
        if (!$user) { 
            $validator['message'] = "Your account is invalid."; 
            $validator['success'] = FALSE; 
            $validator['errormsg'] = TRUE; 
        } else { 
            // 只有用户存在时,才创建userdata
            $userdata = array('a_logged_in' => TRUE, 'adminid' => $user->id); 
            if ($this->insert_logs($user->id, '1', 'Admin Sign In', 0)) { 
                $this->session->set_userdata($userdata); 
                $validator['message'] = "You have successfully logged in."; 
                $validator['success'] = TRUE; 
                $validator['errormsg'] = FALSE; 
            } else { 
                $validator['message'] ="Account has been denied. Please try again."; 
                $validator['success'] = FALSE; 
                $validator['errormsg'] = TRUE; 
            } 
        } 
        echo json_encode($validator); 
    } else { 
        foreach ($_POST as $key => $value) { 
            $validator['messages'][$key] = form_error($key); 
            $validator['success'] = FALSE; 
            $validator['errormsg'] = FALSE; 
        } 
        echo json_encode($validator); 
    } 
}

2. 完善AJAX的错误处理

当前你的AJAX只处理了请求成功的情况,建议添加error回调来排查请求失败的场景(比如500错误):

$.ajax({
    type: "POST",
    url: app_url + "adminlogin/do_login",
    data : formData,
    dataType: "json",
    success:function(res) {
        // 保留现有成功逻辑
        console.log(res);
        if (res.success) {
            console.log(res.message);
            validator("#login_username-error", "");
            validator("#login_password-error", "");
            swal({
                title: "Login Success",
                text: res.message,
                icon: "success",
                button: null
            });
            setTimeout(function() {
                location.href = app_url + "admin";
            }, 2000);
        } else {
            if (res.errormsg) {
                console.log(res.message);
                swal({
                    title: "Login Failed",
                    text: res.message,
                    icon: "warning",
                    button: null
                });
                setTimeout(function() {
                    location.href = app_url + "adminlogin";
                }, 2000);
            }
            if (res.messages.username != "") {
                validator("#login_username-error", res.messages.username);
            } else {
                validator("#login_username-error", "");
            }
            if (res.messages.password != "") {
                validator("#login_password-error", res.messages.password);
            } else {
                validator("#login_password-error", "");
            }
            console.log(res.messages);
        }
    },
    error: function(xhr, status, error) {
        console.error("请求出错:", status, error);
        swal({
            title: "Error",
            text: "An unexpected error occurred. Please check the console for details.",
            icon: "error",
            button: null
        });
    }
});

3. 验证fetch()方法的返回值

确保$this->admin->fetch()方法在没有找到用户时返回空数组而非抛出错误。如果该方法在无结果时会报错,也会导致请求失败,我们已经在修复代码里添加了空值判断来规避这个问题。

额外调试提示

  • 开启CodeIgniter的调试模式(在config.php里设置$config['debug'] = 1;),可以快速看到PHP错误信息,方便排查问题。
  • 打开浏览器开发者工具的Network标签,查看AJAX请求的响应状态和内容,确认是否返回了预期的JSON数据。

内容的提问来源于stack exchange,提问作者lcm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:31:25