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

在外部JS文件中使用CodeIgniter Session遇阻,求解决方案

解决外部JS文件访问CodeIgniter Session与URL问题

首先得明确核心问题:外部JS文件无法直接解析PHP代码,你原来写的<?php echo base_url(); ?>和<?php echo $this->session->userdata('username'); ?>在外部JS里会被当作普通字符串处理,这就是为什么放到视图里能运行,单独拆到JS文件就失效的原因。另外你的AJAX请求里type: 'ajax'是错误的,应该用GET或POST。

下面给你两种可行的解决方案:

方案一:在视图中传递PHP变量到全局作用域

在加载外部JS之前,先在视图的<script>标签里把需要的PHP变量暴露给全局,外部JS就能直接调用了:

1. 视图文件(比如chat_view.php)中的代码

<!-- 先定义全局变量 -->
<script>
window.baseUrl = '<?php echo base_url(); ?>';
window.currentUser = '<?php echo $this->session->userdata('username'); ?>';
</script>
<!-- 再引入外部JS文件 -->
<script src="/path/to/your/external.js"></script>

2. 外部JS文件中的修改

把原来的PHP嵌入代码替换成全局变量,同时修正AJAX的type参数:

function show_msg() { 
    $.ajax({ 
        type: 'GET', // 这里改成GET或POST,根据你的后端接口设置
        url: window.baseUrl + 'index.php/chat/showmsg', 
        async: true, // 不推荐用false,会阻塞浏览器,建议改成true
        dataType: 'json', 
        success: function (data) { 
            var user = window.currentUser; 
            var html = ''; 
            var i; 
            for (i = 14; i >= 0; i--) { 
                if (data[i].user !== user) { 
                    html += '<span style="color:green;font-size:12px;">' + data[i].user + '</span>' + ' ' + '<span style="color:dimgrey;font-size:10px;">' + data[i].date + '</span>' + '<div style="margin-right:25px;margin-bottom:25px;border:0px solid grey; border-radius: 0px 12px 12px 12px; padding:10px;width:auto;background-color:white;;box-shadow:0px 0px 0px 0px grey;direction:rtl;">' + data[i].msg + '</div>'; 
                } else { 
                    html += '<span style="color:green;font-size:12px;">' + "" + '</span>' + ' ' + '<span style="color:dimgrey;font-size:10px;">' + data[i].date + '</span>' + '<div style="margin-left:30px;margin-bottom:25px;border:0px solid grey; border-radius: 8px 0px 8px 8px; padding:10px;width:auto;background-color:#bbf490;box-shadow:0px 0px 0px grey;direction:rtl;">' + data[i].msg + '</div>'; 
                } 
            } 
            $('#show_data').html(html); 
        },
        error: function(xhr, status, error) {
            // 加错误处理方便排查问题
            console.log('AJAX请求出错:', error);
        }
    }); 
}

方案二:从后端接口返回Session数据

如果不想用全局变量,可以让你的chat/showmsg接口同时返回当前用户的信息,这样前端JS就能从AJAX响应里拿到用户名:

1. CodeIgniter控制器(Chat.php)修改

public function showmsg() {
    // 确保session已加载(CodeIgniter默认自动加载,若未关闭)
    $username = $this->session->userdata('username');
    // 原有获取消息的逻辑
    $messages = $this->chat_model->get_recent_messages();
    // 返回包含用户和消息的JSON数据
    echo json_encode([
        'current_user' => $username,
        'messages' => $messages
    ]);
}

2. 外部JS文件修改

从响应里提取用户信息,同时用全局变量处理URL:

function show_msg() { 
    $.ajax({ 
        type: 'GET',
        url: window.baseUrl + 'index.php/chat/showmsg',
        async: true,
        dataType: 'json', 
        success: function (response) { 
            var user = response.current_user; 
            var data = response.messages;
            var html = ''; 
            var i; 
            for (i = 14; i >= 0; i--) { 
                if (data[i].user !== user) { 
                    html += '<span style="color:green;font-size:12px;">' + data[i].user + '</span>' + ' ' + '<span style="color:dimgrey;font-size:10px;">' + data[i].date + '</span>' + '<div style="margin-right:25px;margin-bottom:25px;border:0px solid grey; border-radius: 0px 12px 12px 12px; padding:10px;width:auto;background-color:white;;box-shadow:0px 0px 0px 0px grey;direction:rtl;">' + data[i].msg + '</div>'; 
                } else { 
                    html += '<span style="color:green;font-size:12px;">' + "" + '</span>' + ' ' + '<span style="color:dimgrey;font-size:10px;">' + data[i].date + '</span>' + '<div style="margin-left:30px;margin-bottom:25px;border:0px solid grey; border-radius: 8px 0px 8px 8px; padding:10px;width:auto;background-color:#bbf490;box-shadow:0px 0px 0px grey;direction:rtl;">' + data[i].msg + '</div>'; 
                } 
            } 
            $('#show_data').html(html); 
        }
    }); 
}

额外注意事项

  • 如果你的CodeIgniter开启了CSRF防护,AJAX请求需要带上CSRF token。可以在视图里把token放到全局变量,然后在AJAX的data里添加:data: {<?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'}。
  • 尽量避免使用async: false,它会阻塞浏览器UI,影响用户体验,建议改用异步模式,通过回调、Promise或async/await处理后续逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:19:30