Yii2 $this->registerJs($js); How to pass php variable inside the $js

末鹿安然 提交于 2020-05-27 03:04:09

问题


Below is my ajax script in my view.

$js = <<< JS
    $('.list-link').click(function(){
        $.ajax({
            url: '?r=public/getlist&param1=01&param2=02&param3=03',
            dataType: "json",
            success: function(data) {
                $(".well").html(data.id);                
            }
        })
    });
JS;
$this->registerJs($js);

Now my problem is how am I going to make the values of param1, param2 and param3 dynamic like I am going to pass the params1 to 3 from php variables.


回答1:


You could do it this way:

$url = \yii\helpers\Url::to([
    'public/getlist', 
    'param1' => '01', 
    'param2' => '02', 
    'param3' => '03'
]);

$js = <<< JS
    $('.list-link').click(function(){
        $.ajax({
            url: $url,
            dataType: "json",
            success: function(data) {
                $(".well").html(data.id);                
            }
        })
    });
JS;
$this->registerJs($js);

Of course you can make the number of parameters dynamic as well since it is just an array that gets passed to Url::to().

Official info about the used Heredoc (which allows variable usage) syntax can be found here.




回答2:


robsch's way is great (above answer).

But you can also do this way:

$js = <<< JS
    $('.list-link').click(function(){
        $.ajax({
            url: '?r=public/getlist&amp;param1=$one&amp;param2=$two&amp;param3=$three',
            dataType: "json",
            success: function(data) {
                $(".well").html(data.id);                
            }
        })
    });
JS;
$this->registerJs($js);

where $one, $two and $three are PHP variables.

And don't forgot to replace & with &amp; in Javascript text code string above in $js variable in PHP. It is less error prone and good practice too



来源:https://stackoverflow.com/questions/35124829/yii2-this-registerjsjs-how-to-pass-php-variable-inside-the-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!