2013-02-08 86 views
18

我對我的項目使用了Zend Framework 1.x。我想爲調用者函數創建一個只返回JSON字符串的Web服務。我試圖使用Zend_Controller_Action和施加那些方法:如何僅從Zend返回JSON

1.

$this->getResponse() 
    ->setHeader('Content-type', 'text/plain') 
    ->setBody(json_encode($arrResult)); 

2.

$this->_helper->getHelper('contextSwitch') 
       ->addActionContext('nctpaymenthandler', 'json') 
       ->initContext(); 

3.

header('Content-type: application/json'); 

4.

$this->_response->setHeader('Content-type', 'application/json'); 

5.

echo Zend_Json::encode($arrResult); 
exit; 

6.

return json_encode($arrResult); 
$this->view->_response = $arrResult; 

但是,當我用捲曲得到的結果,它返回用JSON字符串一些HTML標籤包圍。然後我嘗試使用上面的選項Zend_Rest_Controller。它仍然沒有成功。

P.S .:上面的大多數方法都來自Stack Overflow上提出的問題。

回答

32

我喜歡這種方式!

//encode your data into JSON and send the response 
$this->_helper->json($myArrayofData); 
//nothing else will get executed after the line above 
+3

我已經使用了這種方法一段時間了。我不明白需要所有額外的代碼。據我所知,輔助方法可以處理所有的事情。 – David 2013-10-01 19:09:23

+0

在哪裏放這個代碼?在控制器的動作功能? – 2016-03-15 13:55:40

+0

@HarisMehmood你的控制者的行爲是正確的地方,因爲它是處理請求和準備輸出的角色。 – Tim 2016-04-18 11:54:37

7

您的代碼需要禁用佈局,以便停止使用標準頁面模板包裝的內容。但一個更容易的辦法也只是:

$this->getHelper('json')->sendJson($arrResult); 

JSON助手將您的變量編碼爲JSON,設置相應的頭文件和禁用佈局和腳本爲您服務。

9

您需要禁用佈局和視圖渲染。

明確禁止的佈局和視圖渲染:

public function getJsonResponseAction() 
{ 
    $this->getHelper('Layout') 
     ->disableLayout(); 

    $this->getHelper('ViewRenderer') 
     ->setNoRender(); 

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

    // should the content type should be UTF-8? 
    // $this->getResponse() 
    //  ->setHeader('Content-Type', 'application/json; charset=UTF-8'); 

    // ECHO JSON HERE 

    return; 
} 

如果你使用你需要一個JSON上下文到行動的JSON控制器動作助手。在這種情況下,json助手將禁用佈局並查看渲染器。

public function init() 
{ 
    $this->_helper->contextSwitch() 
     ->addActionContext('getJsonResponse', array('json')) 
     ->initContext(); 
} 

public function getJsonResponseAction() 
{ 
    $jsonData = ''; // your json response 

    return $this->_helper->json->sendJson($jsonData); 
} 
+0

Venu的方法更好! – Naelyth 2014-03-19 14:59:47

0

這很容易。

public function init() 
{ 
    parent::init(); 
    $this->_helper->contextSwitch() 
     ->addActionContext('foo', 'json') 
     ->initContext('json'); 
} 

public function fooAction() 
{ 
    $this->view->foo = 'bar'; 
}