How to call codeigniter controller function from view

吃可爱长大的小学妹 提交于 2020-01-08 16:56:42

问题


How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.


回答1:


Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.

A good start for clarifying the best practice is to follow this tutorial:

https://codeigniter.com/user_guide/tutorial/index.html

It's simple, but it really lays out an excellent how-to.

I hope this helps!




回答2:


You can call controller function from view in the following way:

Controller:

public function read() {
    $object['controller'] = $this; 
    $this->load->view('read', $object);
}

View:

// to call controller function from view, do
$controller->myOtherFunct();



回答3:


You can call a controller function with AJAX on your view. In this case, I'm using the jQuery library to make the call.

<script type="text/javascript">
    $.ajax({
            url: "<?=site_url("controller/function")?>",
            type: "post", // To protect sensitive data
            data: {
               ajax:true,
               variableX: "string",
               variableY: 25
               //and any other variables you want to pass via POST
                   },
            success:function(response){
            // Handle the response object
            }
        });
</script>

This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.




回答4:


I would like to answer this question as this comes all times up in searches --

You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.

Your controller may be like below class --

<?php
    class VCI_Controller extends CI_Controller {
    ....
    ....
    function abc($id){
       return $id ;
    }

    }
?>

Now You can call this function in view files as below --
<?php
    $CI =& get_instance();
    $CI->abc($id) ;

?>



回答5:


class MY_Controller extends CI_Controller {

    public $CI = NULL;

    public function __construct() {
        parent::__construct();
        $this->CI = & get_instance();
    }

    public function yourMethod() {

    }

}

// in view just call
$this->CI->yourMethod();



回答6:


views cannot call controller functions.




回答7:


One idea i can give is,

Call that function in controller itself and return value to view file. Like,

class Business extends CI_Controller {
    public function index() {
            $data['css'] = 'profile';

            $data['cur_url'] = $this->getCurrURL(); // the function called and store val
            $this->load->view("home_view",$data);
     }
     function getCurrURL() {
                $currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
            return $currURL;
     }

}

in view(home_view.php) use that variable. Like,

echo $cur_url;



回答8:


I know this is bad.. But I have been in hard situation where it is impossible to put this back to controller or model.

My solution is to call a function on model. It can be do inside a view. But you have to make sure the model has been loaded to your controller first.

Say your model main_model, you can call function on the model like this on your view : $this->main_model->your_function();

Hope this help. :)




回答9:


We can also pass controller function as variable in the view page.

class My_controller extends CI_Controller {
    public function index() {
           $data['val']=3;
           $data['square']=function($val){
                               return $val*$val;
                                   };
    $this->load->view('my-view',$data);
}
}

In the view page

<p>Square of <?=$val?>
   <?php 
     echo $square($val); 
   ?>
</p>

The output is 9




回答10:


it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
    function __construct(){
        parent::__construct();
        $this->load->model('script');
        $this->load->model('alert');

    }public function pledge_ph(){
        $this->script->phpledge();
    }
}
?>

This is the controller class Iris.php and the model class with the function pointed to from the controller class.

<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
    public function __construct() {
        parent::__construct();
        // Your own constructor code
    }public function ghpledge(){
        $gh_id = uniqid(rand(1,11));
        $date=date("y-m-d");
        $gh_member = $_SESSION['member_id'];
        $amount= 10000;
        $data = array(
            'gh_id'=> $gh_id,
            'gh_member'=> $gh_member,
            'amount'=> $amount,
            'date'=> $date
        );
        $this->db->insert('iris_gh',$data);
    } 
}
?>

On the view instead of a button just use the anchor link with the controller name and method name.

<html>
    <head></head>
    <body>
        <a href="<?php echo base_url(); ?>index.php/iris/pledge_ph" class="btn btn-success">PLEDGE PH</a>
    </body>
</html>



回答11:


Try this one.

Add this code in Your View file

$CI     = & get_instance();
$result = $CI->FindFurnishName($pera);

Add code in Your controller File

public function FindFurnishName($furnish_filter)

{

$FindFurnishName        = $this->index_modal->FindFurnishName($furnish_filter);  
$FindFurnishName_val    = '';
foreach($FindFurnishName as $AllRea)
{
    $FindFurnishName_val  .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');

}

where

  1. FindFurnishName is name of function which is define in Your Controller.
  2. $pera is a option ( as your need).



回答12:


if you need to call a controller from a view, maybe to load a partial view, you thinking as modular programming, and you should implement HMVC structure in lieu of plane MVC. CodeIgniter didnt implement HMVC natively, but you can use this useful library in order to implement HMVC. https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

after setup remember:that all your controllers should extends from MX_Controller in order to using this feature.




回答13:


Go to the top of your View code and do it like this :

  <?php
     $this->load->model('MyModelName');
     $MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>

<div class="row">
    Your HTML CODE
</div>


来源:https://stackoverflow.com/questions/9986520/how-to-call-codeigniter-controller-function-from-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!