简体   繁体   中英

Yii registerScript : Adding php parameters to javascript

Hi I'm trying to use an external js, the and I'm using Yii clienScript :

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/some.js');

The problem is, in my external js file, I need to pass a url , for my ajax call. and the url is in php, because I'm using the createAbsoluteUrl() below :

$url = Yii::app()->createAbsoluteUrl("/module/controller/action")

How do I pass the $url as a javascript variable to be used by some.js ? Thanks!

You could create a JS object at the end of your PHP code.

   ...
   ...
   $url = Yii::app()->createAbsoluteUrl("/module/controller/action");
   ...
   Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/some.js');
   <script>
   var WRAPPER = (WRAPPER || {});
   WRAPPER.url = "<?= $url ?>";
   </script>

Then the javascript file some.js should be able to use this as:

var url = WRAPPER.url;

I have done this on CodeIgniter - I'm assuming Yii works similar.

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