codeigniter单击按钮以调用视图

时间:2014-09-21 10:41:40

标签: codeigniter codeigniter-routing

我在codeigniter视图中有2个按钮的视图:

    <div class="btn-main col-md-3 col-md-offset-3"> 
        <button id="simu-mono" type="button" class="btn btn-default">SIMULATION MONO SITE</button>
    </div>
    <div class="btn-main col-md-3"> 
        <button id="simu-multi" type="button" class="btn btn-default">SIMULATION MULTI SITE</button>
    </div>

我想调用另一个控制器,然后在单击按钮时启动视图

我试着通过javascript调用控制器simu_mono,把它放在/controller/simu_mono.php但是不起作用

$(document).ready(function(){
    $("#simu-mono").click(function(){
        type:'GET',
        url:'simu_mono'
    });

    $("#simu-multi").click(function(){

    });
 });

simu_mono.php:

<?php
class simu_mono extends CI_Controller {

    public function index()
    {
            $this->load->view('simu_mono');
            echo 'Hello World!';
    }
}
?>

感谢您的帮助

干杯

2 个答案:

答案 0 :(得分:1)

如果您想重定向,请仅使用以下代码:

$(document).ready(function(){
    $("#simu-mono").click(function(){
         window.location = base_url + "/simu_mono";
    });

    $("#simu-multi").click(function(){
         window.location = base_url + "/simu_multi";
    });
 });

请注意,您可能需要base_url,请使用此代码段在JavaScript变量中加载base_url

<script>
    base_url = <?= base_url()?>
</script>

将上面的代码放在某种始终加载的视图中(在执行任何其他JavaScript代码之前)

附加步骤是设置处理丑陋下划线符号(_)

的路线

类似的东西:

<强> routes.php文件

$route['simu-mono'] = "simu_mono";
$route['simu-multi'] = "simu_multi";

这样您就可以按照以下方式转到页面和控制器:yourserver.ufo/simu-monoyourserver.ufo/simu-multi

答案 1 :(得分:0)

您在javascript中没有进行任何类型的AJAX调用。我假设你正在使用jQuery,所以,你的调用应该是这样的:

$("#simu-mono").click(function(){
    $.ajax({
        url: "http://your-url.com/controller/method",
        type: 'post',     // <- Or get option, whatever you prefer
        dataType: 'json', // <- This is important to manage the answer in the success function
        //data: { param1: "value1", param2: "value2"}, <- You could add here any POST params you wanted
        success: function(data){            
            if (data.view) {
                $('#here_view').html(data.view); // <- '#here_view' would be the id of the container
            }
            if (data.error){
                console.log(data.error);
            }
        }
    });
});

这将调用您的方法,您必须在此处表明您要传递视图:

<?php
class simu_mono extends CI_Controller {

    public function index()
    {
        $return = array(
            'view' => $this->load->view('simu_mono')
        );

        echo json_encode( $return );
    }
}
?>

json_encode将允许您轻松地将vars和数据从PHP传递到您的javascript,并在客户端视图中管理它们。正如你在javascript中看到的那样,我添加了data.error,这是为了防止你有更多的逻辑,可能会改变你发送的视图,如果你发送了数据并想控制它们就发送错误等等。 / p>

当然,在您的javascript中,您可以从点击的按钮中获取网址,并在成功功能的data.view parat中,您可以在屏幕上打印一个模态,将视图发送到容器,无论您想要,XD