php 参考错误:$ 未定义 yii2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21600383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:16:37  来源:igfitidea点击:

ReferenceError: $ is not defined yii2

phpyii2

提问by Dency G B

Adding a javascript inside my view results in the ReferenceError: $ is not defined. I assume that the problem is due to Yii2 injects scripts last on my page. How to fix this?

在我的视图中添加一个 javascript 会导致ReferenceError: $ is not defined. 我认为问题是由于 Yii2 最后在我的页面上注入了脚本。如何解决这个问题?

Or how will I prevent Yii2 from autoloading the script files?

或者我将如何防止 Yii2 自动加载脚本文件?

My view

我的看法

  <?php

   use yii\helpers\Html;
   use yii\helpers\ArrayHelper;
   use yii\helpers\UrlManager;
   use yii\widgets\ActiveForm;
   use backend\controllers\StandardController;

   use backend\models\standard;


   ?>

 <div class="domain-form">

<?php $form = ActiveForm::begin(); ?>

<?php



    <?= $form->field($model, 'clause')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'name')->textarea(['rows' => 6]) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

<?php ActiveForm::end(); ?>

   </div>

    <script type="text/javascript">
    $("document").ready( function () {
    alert("hi");
    });</script>

I need to get this simple script to show an alert after the page loaded. I hav'nt called any of the script file here since yii loads automatically(i think) in the layout by calling

我需要让这个简单的脚本在页面加载后显示警报。我没有在这里调用任何脚本文件,因为 yii 通过调用在布局中自动加载(我认为)

  AppAsset::register($this);

This results in script files to be registered at the end of the page,after my custom script.

这会导致在我的自定义脚本之后在页面末尾注册脚本文件。

How to solve this?

如何解决这个问题?

回答by ippi

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.

Yii2 在您的页面最后注入脚本(jquery 等)。这是有意和希望的。但这意味着 jQuery 将在您的脚本之后加载,因此当您的脚本运行时,jQuery 尚不存在。

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

最简单的快速测试方法是将 yii-scripts(jquery 等)移动到页面的头部。修改assets\AppAsset.php并添加:

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

Done!

完毕!



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

但是在生产中,您通常希望脚本最后加载,而是让 Yii2 处理您的 javascript:

$this->registerJs(
    '$("document").ready(function(){ alert("hi"); });'
);

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

现在 Yii 将处理这个 js 并将它放在任何重要的东西之后(比如 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:

然而,您很快就会注意到 IDE 通常不擅长处理这种语言嵌套(PHP 中的 JavaScript),因此语法突出显示可能会中断。解决它的一种方法是在单独的文件中注册您的脚本:

$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:

如果您想要更多地控制加载脚本的顺序,您可以添加依赖项作为第二个参数,并添加其他选项作为第三个参数:

$this->registerJsFile( 
    'myScript.js', 
    ['\backend\assets\AppAsset'],  
    ['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.

添加脚本的推荐方法是使用AssetBundles。查看assets/AppAssets.php并将您的 js 文件添加到 $js-array 中。

回答by clapas

Whenever you need some assets for a library specific use, register them in the view file like this:

每当您需要某些特定于库的资产时,请在视图文件中注册它们,如下所示:

use yii\web\JqueryAsset;
JqueryAsset::register(this);

Alternatively, if you add yii\web\JqueryAssetto your $dependsattribute inside AppAsset, the asset will be loaded automatically for all your views, given that you registered it in the main layout (by default in Yii2 boilerplate).

或者,如果您添加yii\web\JqueryAsset到您的$depends属性中AppAsset,则资产将自动为您的所有视图加载,前提是您在主布局中注册了它(默认情况下在 Yii2 样板中)。

I wanted to use the yii2-date-range from kartik-v in my project, and did this:

我想在我的项目中使用来自 kartik-v 的 yii2-date-range,并且这样做了:

use kartik\daterange\DateRangePicker;
use kartik\daterange\MomentAsset;
use yii\web\JqueryAsset;

JqueryAsset::register(this);
MomentAsset::register(this);
...
echo DateRangePicker::widget([ 
    'model' => $model, 
    ...
]);

Since I switched to twig templating, I ended up with the following code in my view:

自从我切换到树枝模板后,我最终得到了以下代码:

{{ use('kartik/daterange/DateRangePicker') }}
{{ use('kartik/daterange/MomentAsset') }}
{{ use('yii/web/JqueryAsset') }}
{{ register_jquery_asset() }}
{{ register_moment_asset() }}
...
{{ date_range_picker_widget({ 
    'model': model, 
    ...
   }) }}