2010-09-15 57 views
6

在控制器中,我通過ID從AJAX傳遞生成一個特殊的窗體。表單輸出是JSON。表單創建得很好。但我的問題是顯示這個JSON。怎麼樣?Zend Framework JSON輸出

謝謝。

回答

1

最簡單的方法是從正在執行停止觀點:

function jsonAction() { 
    .... 
    print $json; 
    exit; 
} 

另見檢查http://pl.php.net/json_encode如果你沒有JSON字符串了。

2

JSON是包含在JS風格瓦爾如果你需要訪問該成員在這個字符串,你需要json_decode繩子,讓

$result = json_decode($jsonString); 

但要注意,JSON治療PHP關聯數組像PHP對象的編碼字符串。 ..所以如果你傳遞一個數組,你可以作爲$ result-> memberReference而不是$ result ['memberReference']來訪問它。

+0

當然..unless你只需指定TRUE;如參數號2 :'json_decode($ jsonString,true)',因爲它會返回一個'array'而不是'stdObject'。 – h2ooooooo 2012-09-21 15:17:42

1

可以使用的Zend類

$sData = Zend_Json::encode($aArray); 

或者你可以使用先進的場景,如:

$data = array(
    'onClick' => new Zend_Json_Expr('function() {' 
    . 'alert("I am a valid javascript callback ' 
    . 'created by Zend_Json"); }'), 
'other' => 'no expression', 
); 

$jsonObjectWithExpression = Zend_Json::encode($data,false, 
    array('enableJsonExprFinder' => true) 
); 
+0

如果您使用AJAX獲取json編碼的新數據,那麼它非常有用:) – 2010-09-15 13:16:07

1

的最佳方式TODO這在我看來是一個控制器指定爲您的JSON輸出,那麼你可以這樣做:

class Api_IndexController extends Zend_Controller_Action { 


    public function init() { 
     $this->data = array(); 
    } 


    public function preDispatch() { 
     $this->variables = $this->_getAllParams(); 
    } 


    public function postDispatch() { 
     $this->_helper->json($this->data); 
    } 


    public function __call($name, $args) { 
     return; 
    } 


    public function forumAction() { 

     $this->mapper = new ORM_Model_Mapper_Forum(); 
     $this->model = new ORM_Model_Forum(); 
     $this->dbTable = new ORM_Model_DbTable_Forum(); 

     if (isset($this->variables['id']) && is_numeric($this->variables['id'])) { 
      $output = $this->model->find($this->variables['id']); 

      if ($output->id == null) { 
       return $this->_setError(404); 
      } 
     } else { 
      $output = $this->mapper->fetchAllToArray(); 
     } 

     $this->data = $output; 
    } 


    private function _setError($code=500) { 
     $this->data = array('error' => $code); 
    } 

}