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

Below is my ajax script in my opinion.

$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 I will make the values ​​param1, param2 and param3, how I am going to pass params1 to 3 of php variables.

+4
source share
2 answers

You can do it as follows:

$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 also make the number of parameters dynamic, since it is just an array that is passed to Url :: to () .

Official information on the Heredoc syntax used (which allows the use of variables) can be found here .

+5
source

robsch ( ).

:

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

$one, $two $three - PHP.

& &amp; Javascript $js PHP. .

+1

Source: https://habr.com/ru/post/1626820/


All Articles