|
本帖最后由 youjingqiang 于 2013-12-3 10:48 编辑
1.配置/config/module.config.php:- 'view_manager' => array(
- 'template_path_stack' => array(
- 'album' => __DIR__ . '/../view',
- ),
- 'strategies' => array(
- 'ViewJsonStrategy',
- ),
- ),
复制代码 加入strategies配置。
2.配置action- public function indexAction()
- {
- //return new ViewModel(array(
- // 'albums' => $this->getAlbumTable()->fetchAll(),
- //));
- $results = array();
- $roots = array();
- $albums = $this->getAlbumTable()->fetchAll();
- foreach ($albums as $album){
- $roots[] = array($album->id,$album->title,$album->artist);
- }
- $results = @array('success'=>'true','root' => $roots);
- $results = new JsonModel($results);
- return $results;
- }
复制代码 3.修改vendor\zendframework\zendframework\library\Zend\Json\Json.php
先在Json类中添加一个静态方法:- public static function json_prev($elem) {
- if (is_array($elem)) {
- foreach ($elem as $k => $v) {
- $na[Json::json_prev($k)] = Json::json_prev($v);
- }
- return $na;
- }
- return urlencode($elem);
- }
复制代码 然后修改encode方法:- public static function encode($valueToEncode, $cycleCheck = false, $options = array())
- {
- $valueToEncode = Json::json_prev($valueToEncode);//第一处修改位置
- if (is_object($valueToEncode)) {
- if (method_exists($valueToEncode, 'toJson')) {
- return $valueToEncode->toJson();
- } elseif (method_exists($valueToEncode, 'toArray')) {
- return static::encode($valueToEncode->toArray(), $cycleCheck, $options);
- }
- }
- // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
- $javascriptExpressions = array();
- if (isset($options['enableJsonExprFinder'])
- && ($options['enableJsonExprFinder'] == true)
- ) {
- $valueToEncode = static::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
- }
- // Encoding
- if (function_exists('json_encode') && static::$useBuiltinEncoderDecoder !== true) {
- $encodedResult = json_encode(
- $valueToEncode,
- JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
- );
- } else {
- $encodedResult = Encoder::encode($valueToEncode, $cycleCheck, $options);
- }
- //only do post-processing to revert back the Zend_Json_Expr if any.
- if (count($javascriptExpressions) > 0) {
- $count = count($javascriptExpressions);
- for ($i = 0; $i < $count; $i++) {
- $magicKey = $javascriptExpressions[$i]['magicKey'];
- $value = $javascriptExpressions[$i]['value'];
- $encodedResult = str_replace(
- //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
- '"' . $magicKey . '"',
- $value,
- $encodedResult
- );
- }
- }
- return urldecode($encodedResult);//第二处修改位置
- }
复制代码 现在,访问你的action,就可以看到json格式的返回值了
|
|