1. Inline script registerJs()
Use as follows:
//内部注册js代码 $jsString = "$(function(){ alert(123); });"; $this->registerjs($jsString, View::POS_END);
or
$this->registerJs("var options = ".json_encode($options).";", View::POS_END, 'my-options');
Explanation:
The first element is the js code we want to write in the view file.
The second element is where we decide where to insert this code in the view file.
The third element is the ID that represents this code. It is unique. If there has been an ID before, it will replace or replace the previous one with the same name. If you do not write the last one, element, the js code itself is the Id, and the last element can be ignored.
$this refers to the yii\web\View object, used to manage and render views.
2. External script registerJsFile()
Use as follows:
<?php use backend\assets\AppAsset; use yii\web\View; AppAsset::register($this);//外部引入js文件 $this->registerJsFile(Yii::$app->request->baseUrl . 'js/mytest_js.js', ['depends' => backend\assets\AppAsset::className(), "position"=> $this::POS_END]);
Instructions: Introduce external js files
The first one The parameter is the absolute path of the file Yii::$app->request->baseUrl plus js file.
The second element is the webbing on whom it depends. Here it depends on the backend\assets\AppAsset::className() object.
The third element is the location of the imported file. POS_END indicates that it is introduced before
.
Related tutorial recommendations: yii framework
The above is the detailed content of How to introduce js into yii2.0. For more information, please follow other related articles on the PHP Chinese website!