How to add an external javascript file to a Zend F

2019-03-18 06:18发布

I need to add jQuery and other javascript files to my Zend Framework project. I am trying to do it with an Action controller:-

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();
}

But it is not working.

7条回答
家丑人穷心不美
2楼-- · 2019-03-18 06:54

a good way for that is to use the below code in your controller action lets say u want to include the paginator.js

$this->view->headScript()->appendFile($this->view->baseUrl().'/js/paginator.js');
查看更多
Melony?
3楼-- · 2019-03-18 06:55

Here is how you can use view helpers from within a controller in ZF2 to solve your problem:

public function someAction()
{                 
     $this->getViewHelper('HeadScript')->appendFile($basePath . '/js/somejs.js');    
}

protected function getViewHelper($helperName)
{
    return $this->getServiceLocator()->get('viewhelpermanager')->get($helperName);
}
查看更多
该账号已被封号
4楼-- · 2019-03-18 06:59
 $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');

It is OK with this code in the view. But I don't know is this correct method.

查看更多
一纸荒年 Trace。
5楼-- · 2019-03-18 07:02

you can try this. its works fine for me

//write these lines in your SampleController

public function someAction()
{

$this->getViewHelper('HeadScript')->appendFile('/js/yourjsfile.js');
$this->getViewHelper('HeadScript')->appendFile('/js/jquery/jquery.min.js');
}

// write following method in controller

protected function getViewHelper($helperName)
{

    return $this->getServiceLocator()->get('viewhelpermanager')->get($helperName);
}
查看更多
疯言疯语
6楼-- · 2019-03-18 07:05

Probably the easiest way to use view helpers from within a controller in ZF2 is via the renderer object:

public function someAction()
{                 
     $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
     $renderer->headScript()->appendFile($renderer->baseUrl() . '/js/somejs.js');
}
查看更多
贪生不怕死
7楼-- · 2019-03-18 07:06

You aren't using the view to add jquery:

 $this->view->headScript()->appendFile('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
查看更多
登录 后发表回答