Answer the question
In order to leave comments, you need to log in
How to pass parameters to JS in Yii or write a piece of js code to a controller/component property?
Hello. The situation is as follows:
In the Controller, I created 2 array() parameters: $cssArr and $jsArr. I pass the styles and scripts used on this page to them from the view, and then in the layout using foreach($this->cssArr as style) they are loaded (styles in the layout header, and scripts before the closing one to speed up the page load time). But ran into a problem. I wrote a jQuery plugin, in which, during initialization, it is necessary to pass parameters:
1. unixtime of the beginning of the current day and
2. unixtime of the next day.
Moreover, I ask the server for unixtime, not the client, and only then transfer it to JS. But there was a difficulty with the initialization of this plugin. In the layout, I can't initialize it because the jQuery library is not yet connected (it is connected at the end of the page).
I think we can create a new property (public $jsCode) in the Component and pass the necessary JS code into it from our view, and display the value of this property in the layout after jQuery initialization. But I don’t know how to correctly write this code into a variable so as not to code and escape all the quotes of my JS? Perhaps ob_stat will save, are there any ready-made solutions in Yii? I looked through the documentation and couldn't find anything.
Answer the question
In order to leave comments, you need to log in
Poor search, CClientScript is used for this.
In fact, your story with $cssArr and $jsArr is a cycle, because CClientScript provides all the tools necessary for this.
For example, to add a JS file to the output page, use
www.yiiframework.com/doc/api/1.1/CClientScript#reg...
To add a CSS file,
www.yiiframework.com/doc/api/1.1/CClientScript#reg. ..
And for adding a "raw" script
www.yiiframework.com/doc/api/1.1/CClientScript#reg...
In all of the above methods, you can choose where exactly Yii will push these files and scripts. Specifically for raw scripts, there is CClientScript::POS_READY - i.e. the passed code will be in jQuery ready wrapper and will be executed after jQuery is initialized
I did it this way:
In the controller base class:
class Controller extends CController {
public $jsParams = array();
/* ... */
public function actionIndex() {
$oRequest = Yii::app()->getRequest();
$this->jsParams['csrf'] = array($oRequest->csrfTokenName => $oRequest->getCsrfToken());
}
jsParams = jsParams || {};
console.log(jsParams);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question