日期:2014-05-16  浏览次数:20387 次

JSON简单应用
今天做一个小功能,用ajax来提取数据列表,这里需要用到json。

后台把数组用Zend_Json::encode($value)处理下(ZF框架)或者json_encode()也可以。

前端用JS的for in把数组循环,前端web代码一起拼装放到一个字符串变量里,最后innerHTML
后台代码:
function liulanrecordAction(){
            // 记录最近浏览
            $current_goods_id = $this->_request->getParam('current_goods_id');
            $browse_history = $this->getGoodsBrowseHistory($current_goods_id,Seed_Cookie::getCookie('browse_history'));
            $expiretime = time() + 30*24*60*60;
            Seed_Cookie::setCookie('browse_history',$browse_history,$expiretime,$this->view->seed_Setting['cookie_path'],$this->view->seed_Setting['cookie_host']);
            //------------------------最近浏览过的商品------------------------
            $my_browse = $this->_MyBrowse($browse_history);
            $json_my_browse = Zend_Json::encode($my_browse);
            //$json_my_browse = json_encode($my_browse);
            echo $json_my_browse;
            exit;
        }

前台代码:
//最近浏览记录
    
 $.get("<?php echo $this->baseUrl().'/index/liulanrecord';?>", {current_goods_id: "<?php echo $this->goods['goods_id']?>" },
      function(data){
          var key;
          var htm_str = '';
          for (key in data){
              htm_str += "<div>";
              htm_str += "<p><a href="+data[key]['url']+" target='_blank'><img src="+data[key]['original_img']+" /></a></p>";
              htm_str += "<p class='fred'><b>¥"+data[key]['shop_price']+"</b></p>";
              htm_str += "</div>";
          }
          document.getElementById('liulan').innerHTML = htm_str;
      },'json');