简体   繁体   中英

How to use Javascript/jquery code inside a yii controller action?

I want to call a javascript function inside APIController in my yii projects over a repeated interval.

 public function actionMytimer() {
    Yii::app()->clientScript->registerCoreScript('jquery');
    Yii::app()->clientScript->registerCoreScript('jquery.ui');
    $hello = setInterval(test,1000);
    function test(){
        echo 'hellooo interval';
    }  
}

Its very necessary for me to run the "test" method in a particular time interval.Is it possible?if not then any way to do this?. Please help.Thanks in advnc. Here is the current warning message :

Fatal error: Call to undefined function setInterval() in /Library/WebServer/Documents/MediaPult/protected/controllers/APIController.php on line 449

If you could explain the problem more clearly, It'll be easier for people to provide a good solution.

From what I understand, you want to be able to execute a method on the server side repeatedly. For that, you should output the JavaScript code that does this. It'll be something like this:

<script>
setInterval(function(){
    $.get(<?= Yii::app()->request->baseUrl ?>/actionName");
}, 1000);
</script>

You can not execute javascript functions from php code just like that. You could try something like:

function actionTest(){
  $cs = Yii::app()->clientScript;
  $cs->registerScript('my_script', 'setInterval(test,1000);', CClientScript::POS_READY);
  $this->render('any_view');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM