如何迭代json对象并与html元素绑定。

时间:2014-09-27 05:02:34

标签: jquery json codeigniter

我需要迭代来自我的控制器的JSON对象并将数据绑定到html元素。当我发出警报时,我正在收到物品。 如何迭代这些对象以访问单个数据,以便我可以将其附加到html元素?

我尝试过以下代码。我这里只有几个项目用于演示,实际的数组非常大。

我的控制器:

     public function grid_view_ajax_function()
            {       
                $contacts_details="";
                $this->load->model('contact_model');
                $contacts_details= $this->contact_model->get_all_contacts();
                $result = array();
                $data   = array();
                foreach ($contacts_details as $row_data){
                $data['id']                  =$row_data['contact_id'];
                $data['image']               =$row_data['image'];
                $data['name']                =$row_data['first_name'];
                $data['last_name']           =$row_data['last_name'];    
                array_push($result, $data);

                }
                echo json_encode(array('data' => $result));
            }

main.js文件迭代jquery中的对象:

         $.getJSON(global_base_url + "contact/grid_view_ajax_function",function(data)
            {
            var div_data = ''; 
                $.each(data,function(i,data)
                {       

    div_data +='<div class="col-xl-15" data-id="'+data.index+'"><div class="panel"><div class="panel-heading"><img src="../asset/'+data.picture+'" class="img-responsive desaturate" /></div><div class="panel-body"><div class="name">'+data.name+'</div><div class="email">'+data.email+'</div><div>';
                });

JSON数据:

{
  "data":[
   {
    "id":"1",
    "image":"4.jpg",
    "name":"Mack ",
    "last_name":"Jack",
    "title":"Adminstration",
    "city":"London"
   },
  {
    "id":"2",
    "image":"person-list.png",
    "name":"Renia",
    "last_name":"Jack",
    "title":"Archetectuer"
  }
 ]
}

1 个答案:

答案 0 :(得分:0)

您可以像

一样进行迭代

//here ajax response object is assigned to data variable
var data = {"data":[{"id":"1","image":"4.jpg","name":"Mack ","last_name":"Jack","title":"Adminstration","city":"London"},{"id":"2","image":"person-list.png","name":"Renia","last_name":"Jack","title":"Archetectuer"}]};

var div_data = '';
$.each(data.data,function(i,data) {

  div_data += "<li>"+data.name+"</li>";
  
});
$("ul").html(div_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul></ul>