ZF2如何使用View Helper进行JsonModel Ajax调用

时间:2014-03-19 21:21:13

标签: php ajax zend-framework2 jsonmodel

我使用Zend Framework 2.我使用AJAX从服务器获取数据,如何使用JSON返回格式化数据。 (例如.phtml文件中的多种货币格式$ this-> currencyFormat(1234.56,“TRY”,“tr_TR”)) 我不能从动作中使用视图助手。

我的代码是这样的。 (MyController.php)

<?php
class MyController extends AbstractActionController
{
    public function myAction(){
        $data = array();
        //i want to format this data for multi currency format. as us,fr,tr etc..
        $data['amount'] = '100'; 

        return new JsonModel(data);
    }

}

2 个答案:

答案 0 :(得分:1)

Yargicx,谢谢你提出这个问题。这让我学习了PHP(5.3)的新功能。以下是返回原始问题答案的代码:JSON中的格式化货币。如果你不熟悉可调用类,可能看起来有点奇怪,但我会解释它是如何工作的。

use Zend\I18n\View\Helper\CurrencyFormat;
use Zend\View\Model\JsonModel;

class MyController extends AbstractActionController
{
    public function myAction()
    {
        $data = array();
        //i want to format this data for multi currency format. as us,fr,tr etc..
        $currencyFormatter = new CurrencyFormat();
        $data['amount'] = $currencyFormatter(1234.56, "TRY", "tr_TR");

        return new JsonModel($data);
    }
}

为了达到这一点,我查找了currencyFormat()类中的Zend\I18n\View\Helper\CurrencyFormat方法并注意到这是一个受保护的方法,因此我无法在控制器操作中直接使用它。 / p>

然后我注意到有一个神奇的__invoke()方法(之前从未见过)我在http://www.php.net/manual/en/language.oop5.magic.php#object.invoke查找了PHP文档。事实证明,您可以使用一个对象,就好像它是一个如下所示的函数。注意最后一行:

class Guy
{
    public function __invoke($a, $b)
    {
        return $a + $b;
    }
}

$guy = new Guy();
$result = $guy();

由于__invoke()类的Zend\I18n\View\Helper\CurrencyFormat方法返回对currencyFormat()方法的调用结果,我们可以使用与currencyFormat()相同的参数调用该类方法,导致此答案中的原始代码块。

对于踢,这是__invoke()类的Zend\I18n\View\Helper\CurrencyFormat函数的源代码:

public function __invoke(
    $number,
    $currencyCode = null,
    $showDecimals = null,
    $locale       = null,
    $pattern      = null
) {
    if (null === $locale) {
        $locale = $this->getLocale();
    }
    if (null === $currencyCode) {
        $currencyCode = $this->getCurrencyCode();
    }
    if (null === $showDecimals) {
        $showDecimals = $this->shouldShowDecimals();
    }
    if (null === $pattern) {
        $pattern = $this->getCurrencyPattern();
    }

    return $this->formatCurrency($number, $currencyCode, $showDecimals, $locale, $pattern);
}

答案 1 :(得分:0)

尝试

return new JsonModel('data' => $data);

其他一切都应该有效

修改

$jsonencoded = \Zend\Json\Json::encode($data);//json string

$jsondecode = \Zend\Json\Json::decode($jsonencoded, \Zend\Json\Json::TYPE_ARRAY);

http://framework.zend.com/manual/2.0/en/modules/zend.json.objects.html

这是你的意思吗?

相关问题