是否可以在不使用视图的情况下,在zend控制器功能中打印消息


Is there possible to print a message in a zend controller function, without using a view?

我不知道这个问题是否重复。我在zend完全是个新手。我想使用ajax事件,当我从url中的controller调用controllername/myfunction时,我想返回一条消息。我试过这个:

$.ajax({
    url: "/location/testare",
    type: "POST",
    data: post_array,
    success: function (data, textStatus, jqXHR) {
        //data - response from server
    },
    error: function (jqXHR, textStatus, errorThrown) {
    }
});

在控制器中:

public function testareAction()
{ 
    $this->view->String = 'hello world';
}

firebu给我的回复是:"500内部服务器错误"。有人能帮我吗?

我在Zend Framework 1中使用了这个。MaiKaY的解决方案似乎领先于ZF2:

控制器中,在输出之前,设置头以暴露json输出:

    $this->getResponse()->setHeader('Content-Type', 'application/json');

禁用所有布局内容:

    $this->_helper->layout->disableLayout();

如果您想使用echo 'Zend_Json::encode($yourOutput);而不是使用json的视图,请使用以下内容:

    $this->_helper->viewRenderer->setNoRender(true);

最好的方法是使用jsonModel

看起来像

public function testareAction()
{
    return new JsonModel(array(
        'message' => 'hello world',
    ));
}

使用助手!

示例:

如果您想使用json:返回字符串

$.ajax({
  ...
  dataType: 'json',
  ...
});

在控制器中:

public function testareAction() 
{
    $this->_helper->json('hello world');
}

仅此而已!

更多Zend Framework Helper Json