如何在magento的前端渲染json数据?

时间:2014-04-09 15:11:24

标签: json magento

我在控制器中有一个动作方法

    public function ajaxAction()
    {   
        $this->loadLayout(false);   
        $this->renderLayout();
    }

我想使用前端的json渲染它。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

你可以使用

 public function datajsonAction()
    {  
         $arrayData = array('name'=>'xyz','age'=>'18');

          $$result = Mage::helper('core')->jsonEncode($arrayData);





 $this->getResponse()->setBody(Zend_Json::encode($result));
   }

new Ajax.Request({
    url: "<?php echo Mage::getUrl('test/mycontroller/datajson')",//change your url here
    method: 'Post',
    dataType: "json",
    parameters: {parameter1: 'value1', parameter2: 'value2'}
    onComplete: function(data){
         var json = $.parseJSON(data); // create an object with the key of the array
       alert(json); //it will alert controller data
    }
});

答案 1 :(得分:1)

public function ajaxAction()
    {  
         $arrayData = array('name'=>'xyz','age'=>'18');
         //Json Encode an Array in Magento
         echo $json = Mage::helper('core')->jsonEncode($arrayData);
         return;

        //Json Decode in Magento
       //$array = Mage::helper('core')->jsonDecode($jsonString); 
    }

供您参考ajax调用应

new Ajax.Request({
    url: "<?php echo Mage::getUrl('module/controller/ajax')",//change your url here
    method: 'Post',
    dataType: "json",
    parameters: {parameter1: 'value1', parameter2: 'value2'}
    onComplete: function(data){
         var json = $.parseJSON(data); // create an object with the key of the array
       alert(json); //it will alert controller data
    }
});