从 Zend 控制器传递值并在 JS 响应中获取它

Passing value from Zend controller and fetching it in JS response

本文关键字:响应 JS 获取 控制器 Zend      更新时间:2023-09-26

我有一个Ajax调用,如下所示:

$.post("/user/signindo",{'username':username,"password":password},function(data)
{
// this is what I would like to be able to have in my data object, to be able to access these properties and display them once response is there
alert(data.id);
alert(data.username);
alert(data.firstname);
}

这是我的Zend控制器操作:

public function signindoAction()
{
// doing something here with the values passed from the view
}

该操作基本上不需要返回任何内容,因为它只是检查登录数据是否正常。但是,我在这里需要做的是以某种方式在操作中说,当 Javascript 返回响应时,它会以某种方式获取我需要在 JS 脚本文件中处理的数据。如何使用 Zend 框架执行此操作?有人可以帮我吗?

首先,您需要禁止布局作为响应。为此,请将以下代码放入您的方法Module::onBootstap()中:

public function onBootstrap(MvcEvent $e)
{
    $sharedEvents        = $e->getApplication()->getEventManager()->getSharedManager();
    $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
        $result = $e->getResult();
        if ($result instanceof 'Zend'View'Model'ViewModel) {
            // ban the layout only for ajax
            $result->setTerminal($e->getRequest()->isXmlHttpRequest());
            // To ban the layout for all requests
            // set true : $result->setTerminal(true);
        } else {
            throw new 'Exception('SbmAjax'Module::onBootstap() the result isn't a 'Zend'View'Model'ViewModel');
        }
    });
}

然后在控制器中构建 html 响应,如下所示:

public function signindoAction()
{
    // doing something here with the values passed from the view
    return $this->getResponse()->setContent(Json::encode(array(
        'data' => ...something,
        'success' => 1
    )));
    // to handle errors return response with 'success' => 0
}

就个人而言,我将所有ajax操作包含在特定模块中,并作为整个模块的设置:

$result->setTerminal(true);