如何将外部javascript文件添加到Zend Framework 2应用程序?
我需要将jQuery和其他javascript文件添加到我的Zend Framework项目中。 我正在尝试使用Action控制器: –
public function userinfoAction() { $this->view->headScript()->appendFile($basePath .'/js/validate_jquary.js'); $this->headScript()->appendFile('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'); return new ViewModel(); }
但它没有用。
以下是如何在ZF2中的控制器中使用视图助手来解决您的问题:
public function someAction() { $this->getViewHelper('HeadScript')->appendFile($basePath . '/js/somejs.js'); } protected function getViewHelper($helperName) { return $this->getServiceLocator()->get('viewhelpermanager')->get($helperName); }
$this->HeadScript()->appendFile('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js','text/javascript'); $this->HeadScript()->appendFile('http://localhost/zend/public/js/validate_jquary.js','text/javascript');
在视图中使用此代码即可。 但我不知道这是正确的方法。
从ZF2中的控制器中使用视图助手的最简单方法可能是通过渲染器对象:
public function someAction() { $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface'); $renderer->headScript()->appendFile($renderer->baseUrl() . '/js/somejs.js'); }
你可以试试这个。 它对我来说很好
//在SampleController中写下这些行
public function someAction() { $this->getViewHelper('HeadScript')->appendFile('/js/yourjsfile.js'); $this->getViewHelper('HeadScript')->appendFile('/js/jquery/jquery.min.js'); }
//在控制器中编写以下方法
protected function getViewHelper($helperName) { return $this->getServiceLocator()->get('viewhelpermanager')->get($helperName); }
您没有使用视图添加jquery:
$this->view->headScript()->appendFile('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
一个好方法就是在你的控制器动作中使用下面的代码让我们说你想要包含paginator.js
$this->view->headScript()->appendFile($this->view->baseUrl().'/js/paginator.js');
所有这些都给我带来了大量的错误,$ this-> view-> headScript()完全是关于Zend Framework 1.这对我有用:
在控制器的类定义添加之前在控制器中:
use Zend\View\Helper\HeadScript;
然后你可以在你的控制器中使用这样的东西(确保你可以在任何动作中使用它,而不仅仅是在构造函数中):
/** * @var Zend\View\Helper\HeadScript */ protected $headScript; function __construct() { $this->headScript = new HeadScript(); $this->headScript->appendFile('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js','text/javascript'); }
然后你应该将它添加到你的布局:
headScript(); ?>