简体   繁体   English

如何在 YII2 中将 php 变量传递给 JavaScript 外部文件

[英]How to pass a php variable to JavaScript external file in YII2

I've been trying to pass a php variable's value to JavaScript.我一直在尝试将 php 变量的值传递给 JavaScript。 I can do it when the js code put in the same php view file.当js代码放在同一个php视图文件中时,我可以做到。 but I'dont want to put js code inside the php because its become very tedious to debug or further development.但我不想将 js 代码放在 php 中,因为调试或进一步开发变得非常乏味。

$this->registerJsFile('/js/myJs.js', [JqueryAsset::className()]);

please help.请帮忙。

对于从 php 到 js 的传递变量,您可以使用

 Yii::$app->view->registerJs('var max = "'. $maxMinCost['max'].'"',  \yii\web\View::POS_HEAD);

Another option (compared to pass data with registerJs ) would be to add some data attributes to your HTML elements.另一种选择(与使用registerJs传递数据相比)是向 HTML 元素添加一些data属性。 Quite often this makes sense when an certain element represents a certain corresponding thing.当某个元素代表某个对应的事物时,这通常是有意义的。 Example:例子:

<table>
    <?php foreach($items as $item) { ?>
    <tr data-item-id="<?= $item->id ?>">
        <td>something...</td>
    </tr>
    <?php } ?>
</table>

Then you can have the JS code in a seperate (not generated) file.然后你可以将 JS 代码放在一个单独的(不是生成的)文件中。

Some documentation for data attributes and usage can be found in MDN .可以在MDN 中找到一些有关data属性和用法的文档。

Use an inline JS script before using the external JS script.在使用外部 JS 脚本之前使用内联 JS 脚本。

$inlineScript = 'var key = ' . $value . ';';
$this->registerJs($inlineScript, View::POS_HEAD, 'my-inline-js');

$this->registerJsFile('/js/myJs.js', [
    'depends' => [...],
    'position' => View::POS_BEGIN);

The position constants are used to make sure the JS variable, such as "key" in the above case is defined before the external script. 位置常量用于确保 JS 变量,例如上述情况中的“key”是在外部脚本之前定义的。

There are other ways to pass PHP variables to external JS scripts, such as Ajax.还有其他方法可以将 PHP 变量传递给外部 JS 脚本,例如 Ajax。 Please refer to " How to pass variables and data from PHP to JavaScript? " for more detail.请参阅“ 如何将变量和数据从 PHP 传递到 JavaScript? ”了解更多详细信息。

从 2.0.14 版本开始,可以使用 registerJsVar()。

$this->registerJsVar ('modalTitle', Yii::t('app', 'Update details' ), View::POS_BEGIN);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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