简体   繁体   English

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

[英]ZF3: How to response a JSON from an action function

I'm calling to an action function using angular js. 我正在使用角度js调用动作函数。 I call the action function and receive the parameters correctly, but when I try to response a JsonModel I don't know why Zend Framework responde with a ViewModel. 我调用action函数并正确接收参数,但是当我尝试响应JsonModel时,我不知道为什么Zend Framework会使用ViewModel进行响应。 I think because Zend Framework doesn't detect an Ajax call from Angular JS. 我认为因为Zend Framework没有检测到来自Angular JS的Ajax调用。 So, how can a I call to my action function and Zend Framework detects this call like an Ajax call? 那么,我如何调用我的动作函数和Zend Framework如何像Ajax调用一样检测到这个调用?

angular js: 角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 /application/config/module.config.php

return [
    //...

    'view_manager' => [
        //...

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

/Controller/LoginController.php /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
        ]);             
}

I have found the solution!!! 我找到了解决方案! If you want to have the possibility to return a ViewModel or a JsonModel from an action function, you have to follow the next steps in each module of your application where you want to response a ViewModel or a JsonModel 如果您希望能够从操作函数返回ViewModel或JsonModel,则必须按照应用程序的每个模块中的后续步骤操作,以响应ViewModel或JsonModel

First: In /projectName/module/Application/config/module.config.php 第一:在/projectName/module/Application/config/module.config.php中

return [
    //...

    'view_manager' => [
        //...

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

Second: In /projectName/module/Application/src/Module.php: 第二:在/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);
}

Finally, I have to say that the last line of code $jsonStrategy->attach($view->getEventManager(), 100); 最后,我不得不说最后一行代码$ jsonStrategy-> attach($ view-> getEventManager(),100); in function registerJsonStrategy(MvcEvent $e) originally was ... 在函数registerJsonStrategy(MvcEvent $ e)最初是......

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

You can check this at https://docs.zendframework.com/zend-view/quick-start/#creating-and-registering-alternate-rendering-and-response-strategies 您可以访问https://docs.zendframework.com/zend-view/quick-start/#creating-and-registering-alternate-rendering-and-response-strategies查看此信息。

Bur this line of code returns me this error: Bur这行代码返回给我这个错误:

[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 [Sat Apr 29 00:23:53.416382 2017] [:error] [pid 21286] [client 127.0.0.1:55362] PHP致命错误:未捕获TypeError:传递给Zend \\ EventManager \\ EventManager :: attach()的参数2必须是可调用,整数给定,在第63行的/var/www/html/31juegos/module/Application/src/Module.php中调用,并在/ var / www / html / 31juegos / vendor / zendframework / zend-eventmanager / src /中定义EventManager.php:185 \\ n堆栈跟踪:\\ n#0 /var/www/html/31juegos/module/Application/src/Module.php(63):Zend \\ EventManager \\ EventManager-> attach(对象(Zend \\ View \\)策略\\ 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 - > triggerEvent(Object(Zend \\ Mvc \\ MvcEvent))\\ n#4 /var/www/html/31juegos/vendor/zendframework/zend-mvc/src/Application.php(348):Ze in / var / www /第185行的html / 31juegos / vendor / zendframework / zend-eventmanager / src / EventManager.php

So, I have to change this line of code 所以,我必须改变这行代码

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

By this other line of code: 通过这另一行代码:

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

And the error is fixed!!! 错误是固定的!

Hope it helps to someone!!! 希望对某人有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM