Json 助手專為 AJAX 回應設計,呼叫時會自動:
Content-Type: application/jsonclass FooController extends Zend_Controller_Action {
public function barAction() {
$data = array('status' => 'ok', 'items' => range(1,5));
// 方式 1: 直接呼叫助手 (代理模式)
$this->_helper->json($data);
// 方式 2: 明確呼叫 sendJson() 輸出並結束
$this->_helper->json->sendJson($data);
// 方式 3: 僅取得 JSON 字串,不自動輸出
$json = $this->_helper->json->encodeJson($data);
// 自行處理輸出...
}
}
若需在 JSON 回應外包裝 Layout (如輸出 HTML 頁面內嵌 JSON),所有方法皆支援第二個參數 keepLayouts = true:
// 僅編碼,保留 Layout $json = $this->_helper->json->encodeJson($data, true); // 直接輸出並保留 Layout (較少見) $this->_helper->json->sendJson($data, true);
exit(),後續程式碼不會執行Json 助手以零設定自動化處理 AJAX 回應的標準流程,提供代理呼叫、明確輸出、僅編碼三種彈性介面,並支援保留 Layout 的進階需求,是 Zend Framework 開發 API 與 AJAX 應用的利器。