使用JSON传递数据并在视图页面中检索它

时间:2014-03-26 04:17:48

标签: php json zend-framework

这是我的控制器的一部分,我需要将变量$ coinPacks中的数据传递到我的视图页面


else {
            $coinPacks=$packs->getPacks();
            // print_r($coinPacks);
            echo $this->_helper->json(array('error'=>array('error_code'=>300,'error_message'=>'No enough coins to do correction.','pack'=>$coinPacks)));
        }

这是视图页面部分


alert(JSON.stringify(response.error));
         // foreach($pack as $newpacks)
         // {

            answerContent = answerContent + '<p class="buy-coins" value="1" coins="100">200 &nbsp; &nbsp; &nbsp; &nbsp; $1</p><p>';
            answerContent = answerContent + '<p class="buy-coins" value="3" coins="500">500 &nbsp; &nbsp; &nbsp; &nbsp; $3</p><p>';
            answerContent = answerContent + '<p class="buy-coins" value="5" coins="1000">1000 &nbsp; &nbsp; &nbsp; &nbsp; $5</p><p>';
            answerContent = answerContent + '<p class="buy-coins" value="15" coins="5000">5000 &nbsp; &nbsp; &nbsp; &nbsp; $15</p><p>';
          // } 

我需要获取从视图传递的值并使用该值进行循环并显示数据库中的相应值。我真的不太了解json.please给我一些建议。< / p>


我正在收到这样的提醒


{"error":{"error_code":300,"error_message":"No enough coins to do correction.","pack":{}}}

2 个答案:

答案 0 :(得分:1)

首先尝试使用$coinPacks->toArray()

将其转换为数组

答案 1 :(得分:0)

将其转换为数组


   $coinPacks=$packs->getPacks();
                $coinpacks = array();
                foreach($coinPacks as $coin){
                    $coinpacks['id'] = $coin->id;
                    $coinpacks['number_of_coins'] = $coin->number_of_coins;
                    $coinpacks['price'] = $coin->price;
                    $coins[] = $coinpacks;
                }

并在视图页面中调用它

  var coin = response.pack;                                                                                                                 

  for(var i=0;i<coin.length;i++)                                                                                               
  {                                   
      answerContent = answerContent + '<p class="buy-coins" value="'+coin[i].price+'" coins='+coin[i].number_of_coins+'>'+coin[i].number_of_coins+' &nbsp; &nbsp; &nbsp; &nbsp; $'+coin[i].price+'</p><p>';                  
  }  

  

现在它运作良好