Calling controller method from javascript

2019-06-05 08:21发布

问题:

I need to call a method of controller named test() from a Javascript. Script code is given below:

function changeColor(id, color) 
{
    element = document.getElementById(id);
    qnid = document.form1.pickupFrom.qnid;

    //window.location =  "<?= site_url('controller/test') ?>"
}

Is it possible? And how to pass the parameters?

回答1:

It depends on what parameters youn need to pass. Are they PHP parameters? The you're doing just fine, or better see @Sudhir answer.

If your params come from javascript you shoulnd't use the site_url() function (since when it elaborates and spit out the url, javascript is yet to be executed). It would be much easier to build a URL this way:

function changeColor(id, color) {
            element = document.getElementById(id);
            qnid = document.form1.pickupFrom.qnid;

            window.location =  "<?php echo base_url();?>index.php/controller/test/"+element+"/"+qnid;
}

I'm assuming those two are the parameters you want to pass.



回答2:

You should do it as:

window.location.href =  "<?php echo site_url('yourcontroller_name/function_name/param1/param2') ?>"

Hope it helps