ZF3:如何从动作函数响应 JSON

ZF3: How to response a JSON from an action function

我正在使用 angular js 调用动作函数。我调用了操作函数并正确接收了参数,但是当我尝试响应 JsonModel 时,我不知道为什么 Zend Framework 使用 ViewModel 进行响应。我想是因为 Zend Framework 没有检测到来自 Angular JS 的 Ajax 调用。那么,我如何调用我的操作函数并且 Zend Framework 像 Ajax 调用一样检测到这个调用?

angular js:

self.sendData = function(url, data){
    var promise = $q.defer();
    console.log("Dentro de senDAta!!!");
    var config = {
        headers : {
            "Accept"        :   "application\json",
            "Content-Type"  :   "application\json"
        },
        resposeType : "json"
    };
    $http.post(url, data, config).success(function(response, status, headers, config){
                console.log("dentro de success!!!");
                promise.resolve(response);
            }).error(function(data){
                //Error de sistemas
                console.log("Error en sendData: " + data);
            });
    return promise.promise;        
};  

/application/config/module.config.php

return [
    //...

    'view_manager' => [
        //...

        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],
];

/Controller/LoginController.php

public function loginAction(){
    $request = $this->getRequest();
    $log = new \File\LogWriter();
    $log->writeLog(get_class($this) . "::" . __FUNCTION__ . ": Dentro de loginAction()");
    if ($this->getRequest()->isXmlHttpRequest() === true){
        $log->writeLog(get_class($this) . "::" . __FUNCTION__ . ": Llamada hecha por Ajax");
    }else{
        $log->writeLog(get_class($this) . "::" . __FUNCTION__ . ": Llamada no hecha por ajax");
    }
        $params = json_decode(file_get_contents('php://input'),true);
        $email = $params["email"];
        $password = $params["password"];

        $log->writeLog(get_class($this) . "::" . __FUNCTION__ . ": email: " . $email . " password: " . $password);
        $user = new User($email);
        return new JsonModel([
            "result"    => 0
        ]);             
}

我找到解决办法了!!!如果您希望有可能从动作函数 return ViewModel 或 JsonModel,则必须在您要响应 ViewModel 或 JsonModel 的应用程序的每个模块中执行后续步骤

第一个: 在/projectName/module/Application/config/module.config.php

return [
    //...

    'view_manager' => [
        //...

        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],
];

第二:中/projectName/module/Application/src/Module.php:

public function onBootstrap(MvcEvent $e)
{
    // Register a "render" event, at high priority (so it executes prior
    // to the view attempting to render)
    $app = $e->getApplication();
    $app->getEventManager()->attach('render', [$this, 'registerJsonStrategy'], 100);
}

public function registerJsonStrategy(MvcEvent $e)
{
    $app          = $e->getTarget();
    $locator      = $app->getServiceManager();
    $view         = $locator->get('Zend\View\View');
    $jsonStrategy = $locator->get('ViewJsonStrategy');

    // Attach strategy, which is a listener aggregate, at high priority
    $jsonStrategy->attach($view->getEventManager(), 100);
}

最后不得不说的是最后一行代码$jsonStrategy->attach($view->getEventManager(), 100); in function registerJsonStrategy(MvcEvent $ e) 最初是...

$view->getEventManager()->attach($jsonStrategy, 100);

您可以在 https://docs.zendframework.com/zend-view/quick-start/#creating-and-registering-alternate-rendering-and-response-strategies

查看

Bur 这行代码 return给我这个错误:

[Sat Apr 29 00:23:53.416382 2017] [:error] [pid 21286] [client 127.0.0.1:55362] PHP Fatal error: Uncaught TypeError: Argument 2 passed to Zend\EventManager\EventManager::attach() must be callable, integer given, called in /var/www/html/31juegos/module/Application/src/Module.php on line 63 and defined in /var/www/html/31juegos/vendor/zendframework/zend-eventmanager/src/EventManager.php:185\nStack trace:\n#0 /var/www/html/31juegos/module/Application/src/Module.php(63): Zend\EventManager\EventManager->attach(Object(Zend\View\Strategy\JsonStrategy), 100)\n#1 /var/www/html/31juegos/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Application\Module->registerJsonStrategy(Object(Zend\Mvc\MvcEvent))\n#2 /var/www/html/31juegos/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent))\n#3 /var/www/html/31juegos/vendor/zendframework/zend-mvc/src/Application.php(367): Zend\EventManager\EventManager->triggerEvent(Object(Zend\Mvc\MvcEvent))\n#4 /var/www/html/31juegos/vendor/zendframework/zend-mvc/src/Application.php(348): Ze in /var/www/html/31juegos/vendor/zendframework/zend-eventmanager/src/EventManager.php on line 185

所以,我必须更改这行代码

$view->getEventManager()->attach($jsonStrategy, 100);

通过另一行代码:

$jsonStrategy->attach($view->getEventManager(), 100);

错误已修复!!!

希望对大家有所帮助!!!