如何使用Ajax实现Zend路由

时间:2011-03-18 14:22:24

标签: php ajax zend-framework

我是zend的新手,我找不到在zend中实现Ajax的方法。

一般来说,它很容易制作ajax请求并在页面的所需部分显示响应。但是,我不知道如何做到这一点。

假设在我的索引控制器的index.phtml文件中,我有一个按钮,当我点击它时,我必须向特定的控制器和动作发出ajax请求,并在我的页面中加载相关的控制器动作的视图。

但我无法理解的是如何指定ajax请求的URL以及路由的工作方式。

目前,我发出ajax请求以静态方式加载视图:

  

xmlhttp.open( “GET”, “../应用/视图/脚本/注册/ register.phtml”,TRUE);

仅供参考,我在我的应用程序中使用正则表达式路由,那么使用curl来路由请求会更好吗?

4 个答案:

答案 0 :(得分:7)

首先,您不要直接请求视图。您需要请求特定的控制器操作,例如

/register/register

Zend带有一个名为AjaxContext的动作助手。此帮助程序允许您根据请求类型(XmlHttpRequest)和format参数响应不同的视图,禁用通常存在的任何布局。

要设置它,请在控制器的init()方法

中放置类似的内容
public function init()
{
    $this->_helper->ajaxContext->addActionContext('register', 'html')
                               ->initContext();
}

然后,添加一个带有ajax后缀的视图脚本,例如register/register.ajax.phtml

构造您的AJAX GET请求以包含format=html参数,例如

xmlhttp.open('GET', '/register/register/format/html', true);

xmlhttp.open('GET', '/register/register?format=html', true);

将返回的内容是register.ajax.phtml的呈现内容,没有任何布局。

答案 1 :(得分:2)

除了其他答案所述之外,还有一个URL视图助手功能,可用于调用控制器上的特定操作。因此,您可以使用$this->url(array('controller' => 'your_controller', 'action' => 'your_action'), 'default', true);在“your_controller”控制器上获取“your_action”操作的链接(使用默认路由)。如果您定义了一个路径,也可以指定特定路线而不是“默认路线”。

因此,对于您的示例,您将在视图phtml文件中使用以下内容(如果您使用的是默认路由):

xmlhttp.open("GET","<?php echo $this->url(array('controller' => 'register', 'action' => 'register'), 'default', true);?>");

有关更多信息,请参阅Zend Framework - View Helpers

答案 2 :(得分:1)

您永远不应该直接请求视图。那是错的。请求URI如下:

xmlhttp.open("GET","/register/register");

这意味着“我正在寻找默认模块,注册控制器和注册操作”,换句话说就是RegisterController :: registerAction()。

它与:

相同
xmlhttp.open("GET","/default/register/register");

这是相同的,可以省略默认模块。

Zend Framework知道在哪里查找视图脚本(除非您使用了一些不寻常的目录结构)。

你可以创建一个空白布局并将其用于你的ajax控制器动作(或者Phil建议的,AjaxContent可能更好)。

答案 3 :(得分:1)

我会在这里写一个几乎完整的&#34;如何&#34;在Zendframework 3中实现AJAX调用的指南。 我们需要:

  1. 路线声明
  2. 控制器
  3. 一些javaScript(不是skope,也许我会在其他地方展示它)
  4. 路线声明:

    <?php
    // editing a module.config.php in your project
    // typical lines:
    namespace Ajax2l; // my ajax module name
    use Zend\Router\Http\Segment;
    // ...
    'router' => [
      // ... other routes
      'ajax2lsajaxcall'    => [
        'type'    => Segment::class,
        'options' => [
            'route' => '/ajax2l/ajaxrequest[/:action][/:garbage]',
            // the :action wildcard is a place to have extra parameters
            // the :garbage wildcard is a place to send random strings
            //      to ensure you break cache to get real process for
            //      all your calls, since every call will be different
            'defaults' => [
                'controller' => Controller\AjaxController::class,
                'action'     => 'ajaxrequest'                        
            ]
        ],
        'may_terminate' => true,
        'child_routes'  => [
          // other ajax routes if needed
        ]
    ],
    // I only use one ajax route and one controller for all my sites' ajax 
    // calls because they fire small db actions and reflect them on small
    // parts of my pages. So I think I do not need a route and a controller
    // for each ajax call. Instead, I use a Library and some services to get
    // sets of elementary components and to perform tasks.
    

    控制器 我的Ajax2l模块位于&#34; myzend_project / module&#34; 。目录

    <?php
    // Filename: /module/Ajax2l/src/Controller/AjaxController.php
    namespace Ajax2l\Controller
    
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;
    // No more components are needed
    
    class AjaxController extends AbstractActionController {
      public function ajaxrequestAction(){
        $request = $this->getRequest();
        $content = $request->getContent();
        $isHttpRequest = $this->ifIsValidHttpRequest();
        // if you have a real ajax call you must disable the normal output
        $viewmodel = new ViewModel();
        $viewmodel->setTerminal($is_xmlhttprequest);
        // If not an Ajax call (perhaps from untrusted eyes) serve a forgiven
        // page message
        if(!$isHttpRequest){
          return $this->forgivenPage();
        }
        // Now prepare a response and responds
        $requestParams = $this->preProcessRequest($content);
        // call the logics to process your params
        $output = $this->processRequestParams($requestParams);
        // and send a response
        $response = $this->getResponse();
        $response->setContent($output);
        return $response;
      }
    
      private function ifIsValidHttpRequest($content){
        // I use a small token string to verify if posted data matches 
        // perhaps not the proper way but is fast and works
        $token = 'my_secure_visitor_session_token_identifier';
        return (strpos($content, $token) > 2) ? 1 : 0;
        // the validation is simplified here it has some more
        // complex logics. To ensure validation of requesting source
      }
    
      private function preProcessRequest($content){
        // The logics to know what to do
        // ...
        // here you can identify and set properly the post params
      }
    
      function processRequestParams($requestParams){
        // some logics to process your data
        // ...
        // some logics to create a Json output
        // ...
        return $jsonObject;
      }
    
      protected function forgivenPage(){
        $view = new ViewModel([]);
        // set a forgiven message page as output
        $view->setTemplate('ajax2l/messages/forgiven.phtml');
        // note: the views directory uses lowercase for module names
        return $view;
      }
    }
    

    希望它有所帮助。我失去了很多时间阅读zend ajax没有结果。所以我希望我是最后一个在这个话题上失去时间的人。

    路易斯

相关问题