How to add an external javascript file to a Zend Framework 2 application?

后端 未结 7 2202
梦毁少年i
梦毁少年i 2021-02-07 14:42

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()
{         


        
相关标签:
7条回答
  • 2021-02-07 15:15

    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');
    }
    
    0 讨论(0)
  • 2021-02-07 15:15

    All of the above is giving tons of errors for me and $this->view->headScript() is at all about Zend Framework 1. This works for me:

    in your controller before controller's class definition add:

    use Zend\View\Helper\HeadScript;
    

    and then you may use something like this in your controller (sure you may use it in any action, not only in the constructor):

    /**
     * @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');
    }
    

    and then you should add this to your layout:

    <?php echo $this->headScript(); ?>
    
    0 讨论(0)
  • 2021-02-07 15:18

    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');
    
    0 讨论(0)
  • 2021-02-07 15:19

    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);
    }
    
    0 讨论(0)
  • 2021-02-07 15:23

    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');
    
    0 讨论(0)
  • 2021-02-07 15:37
     $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.

    0 讨论(0)
提交回复
热议问题