我如何展示我的桌子?

时间:2017-07-13 06:06:07

标签: javascript php jquery ajax codeigniter

这是我的index.php视图,我的表被放置了

<table class="striped">
              <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Created at</th>
                </tr>
              </thead>

              <tbody id="showdata">
                <!--<tr>
                  <td>1</td>
                  <td>Alvin</td>
                  <td>Eclair</td>
                  <td>$0.87</td>
                  <td>
                    <a href="javascript:;" class="waves-effect waves-light btn">Edit</a>
                    <a href="javascript:;" class="waves-effect waves-light btn">Delete</a>
                  </td>
                </tr>-->
              </tbody>
</table>

这个我的ajax脚本放在index.php

function showAllEmployee() {
      $.ajax({
        type: 'ajax',
        url: '<?php echo base_url(); ?>index.php/Employee/showAllEmployee',
        async: false,
        dataType: 'json',
        success: function(data) {
          //console.log(data);
          var html = '';
          var i;
          for (i=0; i<data.length; i++) {
            html += '<tr>'+
                  '<td>'+data[i].emp_id+'</td>'+
                  '<td>'+data[i].name+'</td>'+
                  '<td>'+data[i].address+'</td>'+
                  '<td>'+data[i].created_at+'</td>'+
                  '<td>'+
                    '<a href="javascript:;" class="waves-effect waves-light btn" style="margin-right: 10px;" data="'+data[i].emp_id+'">Edit</a>'+
                    '<a href="javascript:;" class="waves-effect waves-light btn" data="'+data[i].emp_id+'">Delete</a>'+
                  '</td>'+
                '</tr>';
          }
          $('#showdata').html(html);
        },
        error: function() {
          alert('Could not get data from database');
        }

      });
    }

这就是我在员工控制器上的内容

public function showAllEmployee()
    {
        $result = $this->em->showAllEmployee();
        echo json_encode($result);
    }

这是我的模特

public function showAllEmployee()
    {
        $this->db->order_by('created_at', 'desc');
        $query = $this->db->get('tbl_employees');
        if($query->num_rows() > 0) {
            return $query->result();
        } else {
            return false;
        }
    }

每当我刷新页面时数据都不显示而不是我遇到错误无法从数据库中获取数据,这是我在我的ajax脚本上设置的条件可能是错误的请帮助

1 个答案:

答案 0 :(得分:0)

在控制器中将标头设置为JSON类型 将您的控制器更改为

public function showAllEmployee(){
    $result = $this->em->showAllEmployee();
    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($result));
}