简体   繁体   English

registerJS 中的数组到字符串转换 - Yii2

[英]Array to string conversion in registerJS - Yii2

In my view I have an array that I can reach by doing:在我看来,我有一个可以通过执行以下操作访问的数组:

$model->stabilimenti;

Now in the same View, in registerJS I'm trying to save this array in a Javascript array, so I can add some clientside checks.现在在同一个视图中,在 registerJS 中,我试图将这个数组保存在一个 Javascript 数组中,这样我就可以添加一些客户端检查。

<?php
$this->registerJs(<<<JS
    jQuery(document).ready(function(){

    let jsArray = [];
    jsArray = $model->stabilimenti;

JS
);

With non-array variables this kind of approach works.对于非数组变量,这种方法有效。

I've also tried to use this notation but without any success.我也尝试使用这种表示法,但没有任何成功。

let jsArray = <?php echo json_encode($model->stabilimenti); ?>;

Is this a lecit operation ?这是合法的手术吗?

You are missing the closing braces and parenthesis }) of the .ready(function(){ function if that is not a typo pasting the code here.如果在此处粘贴代码不是错字,您将缺少.ready(function(){函数的右大括号和括号})

You should parse the php array to javascript staying in php using yii\\helpers\\JSON or json_encode on the array $model->stabilimenti and convert it to json and then assign it to the javascript variable.您应该使用数组$model->stabilimenti yii\\helpers\\JSONjson_encode将 php 数组解析为 javascript 保留在 php 中,并将其转换为 json,然后将其分配给 javascript 变量。 and try loading the code at DOM ready, by using \\yii\\web\\View::POS_READY when registering your script.并尝试在 DOM 就绪时加载代码,在注册脚本时使用\\yii\\web\\View::POS_READY

And you should keep the code separate from each other.并且您应该将代码彼此分开。 See the below code it should work correctly请参阅下面的代码,它应该可以正常工作

<?php
$stabilimenti = \yii\helpers\Json::encode($model->stabilimenti);

$js = <<<JS
jQuery(document).ready(function(){
    let jsArray = {$stabilimenti};
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);

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

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