[英]How to get value from php inside a javascript?
In the below script default values are used. 在以下脚本中,使用默认值。 I would like to use values from database like
<?php $user->location ?>
ie, I want to use users loaction data inside var states
. 我想使用数据库中的值,例如
<?php $user->location ?>
即,我想在var states
内使用用户位置数据。
How do I do it? 我该怎么做?
<script>
$(document).ready(function() {
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California'
];
</script>
Do like this 像这样
<script>
var test = "<?php json_encode($variable); ?>";
</script>
In Yii you can use registerJS in your view file: 在Yii中,您可以在视图文件中使用registerJS :
<?php
$js = "var states = ['" .
implode("','", ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California']) .
"'];";
$this->registerJs($js, View::POS_BEGIN)
// Now states is globally available in JS
?>
<div> ... your view html ... </div>
You can also add this JS code within a controller action instead of placing it into the view file: 您还可以在控制器动作中添加此JS代码,而不是将其放入视图文件中:
public function actionIndex() {
$js = "var states = ['" .
implode("','", ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California']) .
"'];";
$this->view->registerJs($js, View::POS_BEGIN);
return $this->render('index', []);
}
Of course you can replace the array with any array you want. 当然,您可以将阵列替换为所需的任何阵列。 You could use eg:
您可以使用例如:
$states = States::find()->column();
Try this: 尝试这个:
<script type="text/javascript">
$(document).ready(function() {
var states = <?php echo json_encode($user->location); ?>;
});
</script>
<?php
$ar = array('one', 'two', 1, false, null, true, 2 + 5);
?>
<script type="text/javascript">
var ar = <?php echo json_encode($ar) ?>;
// ["one","two",1,false,null,true,7];
// access 4th element in array
alert( ar[3] ); // false
</script>
Thank You!! 谢谢!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.