Home >PHP Framework >YII >How to introduce js into yii2.0

How to introduce js into yii2.0

王林
王林Original
2020-03-11 14:41:522774browse

How to introduce js into yii2.0

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 . &#39;js/mytest_js.js&#39;, [&#39;depends&#39; => 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 36cc49f0c466276486e50c850b7e4956.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn