codeigniter发送id并获取数据库值而不刷新

时间:2014-07-11 05:29:57

标签: php jquery ajax codeigniter

我需要根据id发送id并获取数据库值而不刷新页面。并在我的视图中显示数据,

这是我的观点,

 <div>
 <a href="javascript:void(0);" class="movie" onclick="getSummary(24)">Click on me</a>
 </div>
<script type="text/javascript">
    function getSummary(id)
    {
       $.ajax({

         type: "POST",
         url: '<?php echo site_url('ajax_controller/getBranchDetails'); ?>',
         cache:false,
         data: "id=" + id, // appears as $_GET['id'] @ ur backend side
         success: function(data) {
               // data is ur summary
              $('#summary').html(data);
         }

       });

    }
</script>

控制器

public function getBranchDetails(){

$b_id = $this->input->post('branch_id');
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);


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

我需要在我的视图中显示$ data ['results']

模型

    <?php

    class Ajax_model extends CI_model{

    function getRecords($id)
    {
        $this->load->database();
        $query = $this->db->query("SELECT * FROM companydetails WHERE id='$id'");
        return $query->result();

    }

}

2 个答案:

答案 0 :(得分:0)

请改为尝试:

<script type="text/javascript">
function getSummary(id) {
  $.ajax({
    type: 'POST',
    url: "<?php echo site_url('ajax_controller/getBranchDetails'); ?>", // <-- properly quote this line
    cache: false,
    data: {branch_id: id}, // <-- provide the branch_id so it will be used as $_POST['branch_id']
    dataType: 'JSON', // <-- add json datatype
    success: function(data) {
        // if you need to present this in a html table,
        // likely, you need to use $.each() and build the markup using the json response 
        $('#summary').html(data);
    }
  });
}
</script>

模型:(不要直接在查询字符串中使用变量)

$sql = 'SELECT * FROM companydetails WHERE id = ?';
$query = $this->db->query($sql, array($id));

控制器:

public function getBranchDetails()
{
    $b_id = $this->input->post('branch_id', true);
    $this->load->model('ajax_model');
    $data['results'] = $this->ajax_model->getRecords($b_id);
    echo json_encode($data); // <-- uncomment
}

答案 1 :(得分:0)

试试这段代码,它正在运作。

    <script type="text/javascript">
    function getSummary(id)
    {
     $.post("<?php echo site_url('ajax_controller/getBranchDetails'); ?>",
        {branch_id:id},function(data,status){
              $('#summary').html(data);
    });
    }
    </script>

注意:检查是否包含了jquery.min.js。如果未在视图部分标题中提及以下代码

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">