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

时间:2016-04-25 10:33:56

标签: javascript php jquery ajax zend-framework

我有一个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框架做到这一点?有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

首先,你需要禁止布局作为回应。为此,请将以下代码放在方法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);