简体   繁体   中英

In Yii, pass PHP variables to JavaScript

In my JavaScript (using jQuery) there are a whole set of PHP variables to which I need access. While I've got it working by just producing the JavaScript file as a view, and then using renderPartial() to echo the JavaScript inside the main view.

However, this is obviously not very elegant, so I would like to know the 'Yii' way of doing it. I've been looking at the Assets Manager but that seems to be for static JavaScript files - you can't include PHP in there (unless I'm wrong).

Is there another way of doing it?

There's nothing inherently wrong or inelegant with your approach, and yes assets are static content (JS, CSS, etc) -- unrelated to the issue.

Fundamentally you can only expose the value of a PHP variable in JS by writing it as part of PHP code. If you will only need this value in a limited scope then you could just write it as an inline constant (which is what eg some widgets do). If you need it to be available throughout your JS code the only option is to produce JS code like you do now.

It's not strictly necessary to make a new partial view for your PHP-to-JS variables, but it's also not a bad idea. If you are happy with it, by all means use it.

You may consider registerScript . In my opinion, it is better since there is a param named $position, which can help you control the process output of render().

方法之一是通过一个小脚本和redisterScript()设置全局变量,然后在真实的js中使用这个变量

Setting your variables in a key=>value array and using CJSON::encode works really well. You can access all your variables via the object created by jQuery's parseJSON. For example:

$myVarList = array(
 'nameOne'=>$valueFromAnotherVar,
 'nameTwo'=>$object->coolValue,
 'nameThree'=>$cat->hoursSleptToday()
);

Yii::app()->clientScript->registerScript("myVarList",
    'myVarList = jQuery.parseJSON('.CJSON::encode($myVarList).');'

You can then access the values from the global var.

myVarList.nameOne || myVarList.nameTwo || myVarList.nameThree

Refer to Yii2 - Client Scripts Documentation , you can use registerJS function to pass variables to javascipt. For example:

/* @var $this yii\web\View */
$this->registerJs(
    "var calenderEvents = ".Json::encode($calenderEvents).";", 
    yii\web\View::POS_HEAD, 
    'calender-events-script'
);

Try to do this that way:

$myVarList = array(
'nameOne'=>$valueFromAnotherVar,
'nameTwo'=>$object->coolValue,
'nameThree'=>$cat->hoursSleptToday()
);

$json = addslashes(CJSON::encode($myVarList));

Yii::app()->clientScript->registerScript("myVarList", 'myVarList = jQuery.parseJSON("' . $json . '");');

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