ReferenceError: $ is not defined yii2

舉報 發佈者:tech-3
熱度0票  瀏覽1174次 【共0條評論】【我要評論

from :

Yii2 injects scripts (jquery and the like) last on your page. This is intended and desired. But it means that the jQuery will load AFTER your script, so when your script runs, jQuery does not yet exist.

The easiest way for quick testing is to move yii-scripts (jquery and the like) to the head of the page. Modify assets\AppAsset.php and add this:

public $jsOptions = array(
    'position' => \yii\web\View::POS_HEAD


But in production you usually want the scripts to load last, and instead you let Yii2 handle your javascript:

    '$("document").ready(function(){ alert("hi"); });'

Now Yii will handle this js and place it after anything important (like jQuery).

You'll however soon notice that IDE's are usually bad at handling this kind of language nesting (JavaScript inside PHP) so the syntax highlighting is likely to break. One way to solve it is to register your script in a separate file:

$this->registerJsFile( 'myScript.js' );

If you want even more control about which order to load your scripts, you can add dependencies as your second argument, and additional options as the third:

    ['position' => '\yii\web\View::POS_END']

If you for some reason absolutely want the script to be rendered inline you can do:

$this->registerJs( $this->renderPartial('myScript.js') );

The recommended way to add your scripts is to use AssetBundles. Look in assets/AppAssets.phpand add your js-file to the $js-array.

上一篇 下一篇