Codeigniter:使用Ajax检索按钮单击时的数据

时间:2014-08-19 21:18:23

标签: javascript php jquery ajax codeigniter

我有一个简单的网页,在刷新页面时会从我的数据库生成一个随机引用。我希望实现一些AJAX和JQuery,以便通过按钮生成引号,而不必刷新页面。我做了一些研究,但我不知道如何在Codeigniter中实现这一点。我目前的代码低于......

页面控制器:

public function index() {
    $this->load->model('quote_model', '', TRUE);
    $data['quotes'] = $this->quote_model->getRandom();
    $this->load->view('home', $data);
}

观点:

<?php include ('layout/header.php'); ?>

<div class="container-fluid">
<div class="row">
    <div class="col-md-4 quote-holder">
        <img src="application/assets/alan1.jpg" alt="..." class="img-circle img-responsive">
        <br>
        <blockquote class="text-center">
            <p><?php echo $quotes[0]['quote']; ?></p>
            <footer class="text-center"><?php echo $quotes[0]['character_name']; ?> in <cite title="Source Title"><?php echo $quotes[0]['series_name']; ?></cite></footer>
        </blockquote>
        <button type="button" class="btn btn-default center-block">Generate quote</button>
    </div>
</div>

<?php include ('layout/footer.php'); ?>

以下是模型中我从以下位置检索数据的函数:

function getRandom() {
    $query = $this->db->query("
       SELECT * FROM quotes, characters, series
       WHERE quotes.series_id = series.series_id AND quotes.character_id = characters.character_id
       ORDER BY rand() 
       LIMIT 1
    ");
     return $query->result_array();
}

我应该只使用这样的东西吗?

$("button").click(function(){
   $.get( "Page/index", function( data ) {
     //output data to page element...
   }
});

2 个答案:

答案 0 :(得分:0)

getI会做类似:controller:

  public function callme()
{
    $this->load->model('quote_model);
    $data['quotes'] = $this->quote_model->getRandom();
}

然后在我的页脚中:

condole.log("click button")
var_url = "controller/callme" // the url to the controller and method
$.get({
       url: url

      })

但是,我很擅长编程,更糟糕的是jquery:D

答案 1 :(得分:0)

为偏移

创建隐藏输入
<button onclick="showmore()" value="showmore" />
<input type="hidden" name="offset" id="offset" value="15"/>

现在你的Ajax电话

function showmore(){
$.ajax({
    url:my_controller/showmore,
    data:{
      offset :$('#offset').val()

    },
    type:json, 
    success :function(data){
        $('#show-more').prepand(data.view)
        $('#offset').val(data.offset)
    }
})

}

您的控制器

function showmore(){
  $limit = '10';
  $offset = $this->input->get('offset');

  $result  = $this->yourmodel->getdata($offset,$limit);
  $data['view'] = $result;
  $data['offset'] =$offset +10;
  echo json_encode($data);
}

你的模特

$query = $this->db->get('your_table', $limit, $offset); 
        $data=$query->result_array();
        return $data;