【问题标题】:Passing a variable from one controller method to another将变量从一个控制器方法传递到另一个
【发布时间】:2012-09-12 06:54:04
【问题描述】:

我正在使用 CodeIgniter 框架。我加载了一个主视图,其中包含几个选项卡,这些选项卡通过 AJAX 在<div> 中加载其他视图。我的控制器类如下所示:

class MainController extends MY_Controller
    function main($id=0)
    {
        $this->load->model('main_model');
        $this->data['info'] = $this->main_model->foo($id);
        $this->load->view('main_view', $this->data);
    }

    function tab1()
    {
        $this->load->view('tab1_view', $this->data);
    }

}

我通过调用mywebapp/main/123 加载主页。 id 可用于main 方法和main_view。但是当我单击选项卡时,我也想在<div> 和main_view 中使用id。最好的方法是什么?也许有什么方法可以使这个变量对控制器中的每个方法都是全局的?

我使用 jQuery 加载选项卡:

$("#div").load(mywebapp/tab1);

【问题讨论】:

    标签: php jquery codeigniter shared-state


    【解决方案1】:

    使用__construct()

    class MainController extends MY_Controller
    
    protected $_id;
    
        public function __construct()
    {
            $this->_id = $this->uri->segment(3);
    }
    
        function main()
        {
            $this->load->model('main_model');
            $this->data['info'] = $this->main_model->foo($this->_id);
            $this->load->view('main_view', $this->data);
        }
    
        function tab1()
        {
            //available here too
            echo $this->_id;
            $this->load->view('tab1_view', $this->data);
        }
    }
    

    或者,您可以将其更改为使用:$this->uri->uri_to_assoc(n),它们是 /method/controller/key/value/key2/value2 之后的键值对

    示例:

    /user/search/name/joe/location/UK/gender/male
    
    [array]
    (
        'name' => 'joe'
        'location'  => 'UK'
        'gender'    => 'male'
    )
    

    【讨论】:

    • 遗憾的是,这对我不起作用。当我使用 $("div").load(mywebapp/tab1)` 加载“子视图”时,MainController 再次加载,$this->_id 被覆盖为空($this->uri->segment(2) 是 tab1)
    • 所以通过它。 $('div').load('mywebapp/tab1?somevar==$this->_id;?>');如果某个 var 存在,覆盖 $this->_id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    相关资源
    最近更新 更多