1

在 zend 框架 2 中,我在 module.config.php 中有以下配置:

'strategies' => array(
    'ViewJsonStrategy',
)

我的控制器是:

use Zend\View\Model\JsonModel;
$view = new JsonModel(array(
            'username' =>  ucfirst( $username ),
            'datarr' => array(

                'a' => 'A',
                'b' => 'B',
                'c' => 'C',
                'd' => 'D',

            ),
        ));

在我看来,刚刚得到:

{ "username" : "Reynold", "datarr" : {"a":"A", "b":"B", "c":"C", "d":"D" } }

当我使用时 $view = new ViewModel();,我是正确的,而在使用JsonModel时我得到了上面的,谁能帮我找出我做错了什么?

4

1 回答 1

0

这没有什么问题。JsonModel 用于 ajax 请求,而 ViewModel 用于普通的 http 请求。

您可以将来自 JsonModel 的响应用作 javascript 对象。这是一个使用 jquery 的示例:

$.ajax({
    url: yourUrl,
    success: function(d) {
        console.log(d.username);
        console.log(d.datarr.a);
    }
});

在您的控制器中,您可以检查它是否是这样的 ajax 请求:

if($this->getRequest()->isXmlHttpRequest()) {
   // return json-model
}
于 2014-09-17T15:48:45.197 回答