简体   繁体   中英

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.

<?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.

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. and try loading the code at DOM ready, by using \\yii\\web\\View::POS_READY when registering your script.

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);

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