在Yii 2.0中添加jquery

如何在Yii 2.0中将jQuery添加到我的页面?

在Yii 1.x中你可以使用:

Yii::app()->clientScript->registerCoreScript('jquery'); 

我已经尝试用自己的方法覆盖View类,并尝试在那里注册jQuery,但它没有显示在我的html页面中:

 namespace frontend\components; /** * This is the base view object, it extends the yii\web\View so you can add custom view stuff here. */ class BaseView extends \yii\web\View { public function init() { parent::init(); \yii\web\JqueryAsset::register($this); } } 

您使用正确的方式注册jquery我想。 但是如果你注册了至少一个位置= POS_READY的js,那么基础Yii 2.0视图类会自动注册jquery(在视图中):

 $this->registerJs($js, \yii\base\View::POS_READY); 

或在任何控制器或小部件内:

 $this->getView()->registerJs($js, \yii\base\View::POS_READY); 

因此,如果你使用任何javascript代码或文件(你使用它,因为你需要jquery)你可以完全摆脱JqueryAsset。

如果要从控制器中包含js文件,也可以使用它

  public function actionIndex() { $this->getView()->registerJsFile('js/fileinput.js'); return $this->render('index', [ 'model' => $model, ]); } 

如果您想了解更多详情,请查看此链接

http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html

解决了! 我忘了将视图方法放在我的视图文件中:( $this->beginBody()等)