代码符:将数据从控制器传递到视图

2022-08-30 13:49:43

我想从名为的控制器传递,但是我得到了一个未定义的变量错误。$datapollresults_view

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Poll extends CI_Controller {

    public function __construct()
       {
            parent::__construct();
            $this->load->database();
            $this->load->helper('form');
       }

    public function index()
    {

        $this->load->view('poll_view',$data);
    }

    public function vote()
    {
        echo "Voting Successfull";
        $this->db->insert('votes',$_POST);
    }

    public function results()
    {
        echo "These are the results";
        //$query = $this->db->get('votes');
        $data = "hello";
        $this->load->view('results_view', $data);

    }
}

Results_view.php

<html>
<?php echo $data; ?>
</html>

答案 1

$data应该是数组或对象:http://codeigniter.com/user_guide/general/views.html

$data = array(
    'title' => 'My Title',
    'heading' => 'My Heading',
    'message' => 'My Message'
);

$this->load->view('results_view', $data);

results_view.php

<html>
<?php 
//Access them like so
echo $title.$heading.$message; ?>
</html>

答案 2

简单来说,

$data['a']在控制器中变为在您的视图中。(不会存在于您的视图中,只有索引将变为可用)$a$data

例如:

Controller:    
$data['hello']='hellow world';

view:
echo $hello;

推荐