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

如何加载CodeIgniter控制器方法所提供的网页

在CodeIgniter 3.1.7中实现Training控制器并加载网页的步骤

嘿,刚上手CodeIgniter 3的话,咱们一步步来完成控制器编写、视图创建,最后成功访问网页:

1. 补全你的Training控制器

你已经创建了/application/controllers/training.php,现在把它补全成符合CI3规范的代码:

<?php
// 防止直接访问文件
defined('BASEPATH') OR exit('No direct script access allowed');

// 控制器类名首字母大写是CI3的规范要求
class Training extends CI_Controller {

    // 构造函数,用于初始化加载模型等基础操作
    public function __construct() {
        parent::__construct();
        // 加载你已经写好的training_model模型
        $this->load->model('training_model');
    }

    // 默认访问方法(当URL仅指定控制器名时,自动调用此方法)
    public function index() {
        // 调用模型方法获取所有培训数据
        $data['trainings'] = $this->training_model->get_all_trainings();
        
        // 加载视图文件,并把数据传递给视图渲染
        $this->load->view('training_view', $data);
    }
}
?>

2. 创建对应的视图文件

控制器需要把数据渲染成网页,所以在/application/views目录下创建training_view.php文件,示例代码如下(记得替换成你training表的实际字段):

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>培训列表</title>
</head>
<body>
    <h1>所有培训信息</h1>
    
    <?php if (!empty($trainings)): ?>
        <table border="1" cellpadding="8">
            <tr>
                <!-- 替换成你数据表的实际字段,比如id、title、create_time等 -->
                <th>ID</th>
                <th>培训标题</th>
                <th>举办日期</th>
            </tr>
            <?php foreach ($trainings as $item): ?>
                <tr>
                    <td><?php echo $item->id; ?></td>
                    <td><?php echo $item->title; ?></td>
                    <td><?php echo $item->hold_date; ?></td>
                </tr>
            <?php endforeach; ?>
        </table>
    <?php else: ?>
        <p>暂无培训数据</p>
    <?php endif; ?>
</body>
</html>

3. 访问你的网页

现在可以通过浏览器访问页面了,CI3的默认URL结构是:
http://localhost/你的项目文件夹名/index.php/training

举个例子:如果你的项目放在XAMPP的htdocs/ci_demo文件夹下,那么访问URL就是:
http://localhost/ci_demo/index.php/training

小优化提示:

如果想去掉URL里的index.php,可以在项目根目录创建.htaccess文件(需要开启Apache的rewrite模块),内容如下:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

然后修改application/config/config.php里的$config['index_page'] = '';即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:08:18