【问题标题】:ZF3: How to response a JSON from an action functionZF3:如何从动作函数响应 JSON
【发布时间】:2017-04-28 20:46:34
【问题描述】:

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

角度 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
        ]);             
}

【问题讨论】:

    标签: php angularjs zend-framework3


    【解决方案1】:

    我找到了解决办法!!!如果您希望有可能从操作函数返回 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);
    }
    

    最后不得不说,函数registerJsonStrategy(MvcEvent $e)中最后一行代码$jsonStrategy->attach($view->getEventManager(), 100);原来是. ..

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

    你可以在https://docs.zendframework.com/zend-view/quick-start/#creating-and-registering-alternate-rendering-and-response-strategies查看这个

    这行代码给我返回了这个错误:

    [2017 年 4 月 29 日星期六 00:23:53.416382] [:error] [pid 21286] [client 127.0.0.1:55362] PHP 致命错误:未捕获的类型错误:传递给 Zend\EventManager\EventManager::attach() 的参数 2 必须是可调用的, 给定整数,调用 /var/www/html/31juegos/module/Application/src/Module.php 在第 63 行 并定义在 /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\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(对象(Zend\Mvc\MvcEvent))\n#4 /var/www/html/31juegos/vendor/zendframework/zend-mvc/src/Application.php(348): 泽仁 /var/www/html/31juegos/vendor/zendframework/zend-eventmanager/src/EventManager.php 在第 185 行

    所以,我得改一下这行代码

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

    通过这另一行代码:

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

    错误已修复!!!

    希望对某人有所帮助!!!

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多