In Yii, pass PHP variables to JavaScript

前端 未结 6 517
面向向阳花
面向向阳花 2021-01-20 04:11

In my JavaScript (using jQuery) there are a whole set of PHP variables to which I need access. While I\'ve got it working by just producing the JavaScript file as a view, an

相关标签:
6条回答
  • 2021-01-20 04:34

    Setting your variables in a key=>value array and using CJSON::encode works really well. You can access all your variables via the object created by jQuery's parseJSON. For example:

    $myVarList = array(
     'nameOne'=>$valueFromAnotherVar,
     'nameTwo'=>$object->coolValue,
     'nameThree'=>$cat->hoursSleptToday()
    );
    
    Yii::app()->clientScript->registerScript("myVarList",
        'myVarList = jQuery.parseJSON('.CJSON::encode($myVarList).');'
    

    You can then access the values from the global var.

    myVarList.nameOne || myVarList.nameTwo || myVarList.nameThree
    
    0 讨论(0)
  • 2021-01-20 04:37

    There's nothing inherently wrong or inelegant with your approach, and yes assets are static content (JS, CSS, etc) -- unrelated to the issue.

    Fundamentally you can only expose the value of a PHP variable in JS by writing it as part of PHP code. If you will only need this value in a limited scope then you could just write it as an inline constant (which is what e.g. some widgets do). If you need it to be available throughout your JS code the only option is to produce JS code like you do now.

    It's not strictly necessary to make a new partial view for your PHP-to-JS variables, but it's also not a bad idea. If you are happy with it, by all means use it.

    0 讨论(0)
  • 2021-01-20 04:38

    Try to do this that way:

    $myVarList = array(
    'nameOne'=>$valueFromAnotherVar,
    'nameTwo'=>$object->coolValue,
    'nameThree'=>$cat->hoursSleptToday()
    );

    $json = addslashes(CJSON::encode($myVarList));

    Yii::app()->clientScript->registerScript("myVarList", 'myVarList = jQuery.parseJSON("' . $json . '");');

    0 讨论(0)
  • 2021-01-20 04:47

    Refer to Yii2 - Client Scripts Documentation, you can use registerJS function to pass variables to javascipt. For example:

    /* @var $this yii\web\View */
    $this->registerJs(
        "var calenderEvents = ".Json::encode($calenderEvents).";", 
        yii\web\View::POS_HEAD, 
        'calender-events-script'
    );
    
    0 讨论(0)
  • 2021-01-20 04:51

    You may consider registerScript. In my opinion, it is better since there is a param named $position, which can help you control the process output of render().

    0 讨论(0)
  • 2021-01-20 04:54

    The one of approaches is to set global variable by a small script and redisterScript(), and then use this variable in real js

    0 讨论(0)
提交回复
热议问题