如何使用AJAX请求从代码点火器模型显示数据

时间:2016-07-28 13:52:05

标签: php jquery ajax codeigniter codeigniter-2

我的Codeigniter网站有侧面板,当我点击或选择侧面板中的任何选项时,主面板上会显示相应的内容。

首页URLhttp://localhost/main/userinfo/allusers 当我点击女性按钮URLhttp://localhost/main/userinfo/female

enter image description here 当我发出Ajax请求时,我有以下输出。我在哪里犯了错误? enter image description here

控制器(main.php)

class Main extends CI_Controller {
public function __construct() {
    parent::__construct();           
    $this->load->model('userinfo_model'); 
}
public function index() {}   
public function userinfo($gender) {
    $this->load->view('home/inc/header_view');        
    $usermain_data['user_info'] = $this->userinfo_model->get_data($gender);
    $this->load->view('home/main_view', $usermain_data);
}

模型(userinfo_model.php)

class Userinfo_model extends CI_Model {
function __construct() {
    // Call the Model constructor
    parent::__construct();
}
function get_data($gender) {      
    $this->db->select('*'); 
    if($gender == 'female'){
        $this->db->where('gender', 0); 
    }
    elseif($gender == 'male'){
        $this->db->where('gender', 1); 
    }
    elseif($gender == 'allusers'){
        $gNames = array(0, 1);             
        $this->db->where_in('gender', $gNames);
    } 
    else {
        redirect(base_url() . 'main/userinfo/allusers');
    }
    $query = $this->db->get('tble_userinfo');
    //return $query->result();
    echo(json_encode($query->result())); 
}}

查看(main_view.php)

<div class="container">  
<div class="row">
    <div class="col-md-3 side_menu">
        <div class="btn-group" data-toggle="buttons">
            <label class="btn btn-default gender-label" id="lbl-female" onclick="displayfemale()">
                <input type="radio" name="options" id="option1" autocomplete="off">
                <span>Female</span>
            </label>
            <label class="btn btn-default gender-label" id="lbl-male" onclick="displaymale()">
                <input type="radio" name="options" id="option2" autocomplete="off">
                <span>Male</span>
            </label>
        </div> <br> <br> 
        <label class="label nav-label">Age</label>
        <select class="btn nav-age-select" id="ageSelect1" autocomplete="off">
            <option value="18">18</option>
            <option value="19">19</option>
            <option value="20">20</option>       
            <option value="21"  selected="selected">21</option>
            <option value="22">22</option>
            <option value="23">23</option>       
            <option value="24">24</option>
            <option value="25">25</option>

        </select>
        <label class="label nav-label label-to">To</label>
        <select class="btn nav-age-select" id="ageSelect2" autocomplete="off">
            <option value="18">18</option>
            <option value="19">19</option>
            <option value="20">20</option>       
            <option value="21">21</option>
            <option value="22">22</option>
            <option value="23">23</option>       
            <option value="24">24</option>
            <option value="25" selected="selected">25</option>
        </select>

    </div>
    <div class="col-md-8 main-body">
        <div id="userdata">
            <?php
            //foreach ($user_info as $info) {
                //confuse of adding date here with ajax
                //echo $info->content . '<br />' . $info->added_date .'<br />'; 
            //}
            ?>
        </div>         
    </div>
</div>      

<script type="text/javascript"> 
$(document).ready(function () {
    var ajaxUrl     = '<?php echo base_url(); ?>' + 'main/userinfo';        
    var gender      = 'allusers'; // defual 1 for female and male both together

    getAjax(ajaxUrl, gender); 

    $("#lbl-female").click(function () {   
        gender = 'female';
        getAjax(ajaxUrl, gender);  
    });
    $("#lbl-male").click(function () {   
        gender = 'male';
        getAjax(ajaxUrl, gender);  
    });
});     
function getAjax(ajaxUrl, gender){       
    ajaxUrl = ajaxUrl + '/' + gender;                
    $.ajax({
        url: ajaxUrl,
        dataType: "JSON",
        type: "POST",
        success: function (retdata) { 
            $("#userdata").html('');                 
            if(retdata.hasOwnProperty("error")){
                $("#userdata").html('<div">' + retdata.msg + '</div>');  
            }  
            else{    
                $.each(retdata, function(i){    
                    $("#userdata").append(retdata[i].content + '<br>');                       
                });                         
            }

        }
    });          
}

1 个答案:

答案 0 :(得分:4)

这个答案最初会main加载两种性别。性别按钮不会使用多个性别特定的URL,而是返回所选性别的html,并动态更改页面的html。

main_view.php(包含Javascript)

<div class="container">  
  <div class="row">
    <div class="col-md-3 side_menu">
      <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default gender-label" id="lbl-female">
          <input type="radio" name="options" id="option1" autocomplete="off">
          <span>Female</span>
        </label>
        <label class="btn btn-default gender-label" id="lbl-male">
          <input type="radio" name="options" id="option2" autocomplete="off">
          <span>Male</span>
        </label>
      </div> <br> <br> 
      <label class="label nav-label">Age</label>
      <select class="btn nav-age-select" id="ageSelect1" autocomplete="off">
        <option value="18">18</option>
        <option value="19">19</option>
        <option value="20">20</option>       
        <option value="21"  selected="selected">21</option>
        <option value="22">22</option>
        <option value="23">23</option>       
        <option value="24">24</option>
        <option value="25">25</option>

      </select>
      <label class="label nav-label label-to">To</label>
      <select class="btn nav-age-select" id="ageSelect2" autocomplete="off">
        <option value="18">18</option>
        <option value="19">19</option>
        <option value="20">20</option>       
        <option value="21">21</option>
        <option value="22">22</option>
        <option value="23">23</option>       
        <option value="24">24</option>
        <option value="25" selected="selected">25</option>
      </select>
    </div>
    <div class="col-md-8 main-body">
      <div id="userdata">
        <?php
        foreach($user_info as $info)
        {
          echo $info->content.'<br />'.$info->added_date.'<br />';
        }
        ?>
      </div>         
    </div>
  </div>
</div>
<script>
  $(document).ready(function () {
  var ajaxUrl = '<?php echo base_url(); ?>' + 'main/userinfo';

  $("#lbl-female").click(function () {
    getAjax(ajaxUrl, 'female');
  });
  $("#lbl-male").click(function () {
    getAjax(ajaxUrl, 'male');
  });
});
function getAjax(URL, gender) {
  $.ajax({
    url: URL,
    data: {gender: gender},
    dataType: "html",
    type: "POST",
    success: function (retdata) {
      $("#userdata").html(retdata);
    }
  });
}
</script>

请注意$.ajax选项中的行

data: {gender: gender},

我们将数据“发布”到控制器,将在AJAX响应函数中使用$this->input->post("gender");检索。

模型不应做任何事情,只能返回要使用的控制器的数据。根据返回的数据确定发生的情况是控制器的工作。因此,redirect()调用已被删除。

Userinfo_model.php

class Userinfo_model extends CI_Model
{
  function __construct()
  {
    // Call the Model constructor
    parent::__construct();
  }

  // Note the default value for argument $gender. 
  // This means you do not have to pass an argument.
  // If you don't pass one, then !empty($gender) === FALSE
  function get_data($gender = NULL)
  {
    $this->db->select('*');

    //select based on gender. 
    //If no $gender then a "where" clause is not needed and both genders are selected
    if(!empty($gender)) 
    //an argument was provided
    {
      if($gender == 'female')
      {
        $this->db->where('gender', 0);
      }
      else
      {
        $this->db->where('gender', 1);
      }
    }

    $query = $this->db->get('tble_userinfo');
    return $query->result();
  }
}

最后,我们到达控制器。 index()将通过调用get_data()来显示两种性别,而不会将参数传递给模型。之后,AJAX响应者userinfo()将返回所需性别的html到ajax success函数。 success函数将使用从userinfo()回显的新html替换现有的html。

class Main extends CI_Controller
{
  public function __construct()
  {
    parent::__construct();
    $this->load->model('userinfo_model');
  }

  public function index()
  {
    $usermain_data['user_info'] = $this->userinfo_model->get_data();
    $this->load
        ->view('home/inc/header_view')
        ->view('home/main_view', $usermain_data);
  }

  //Only used to respond to an AJAX request
  public function userinfo()
  {
    $gender = $this->input->post('gender');

    if(empty($gender))
    {
      $out =  "No Users Found";
    }
    else
    {
      $user_info = $this->userinfo_model->get_data($gender);
      $out = "";

      foreach($user_info as $info)
      {
        $out .= $info->content.'<br />'.$info->added_date.'<br />';
      }
    }
    echo $out;
  }

}

到目前为止,这似乎相当安全。唯一的用户输入是性别值。 (永远不要相信用户输入)如果有人尝试传递字符串“female”以外的值,数据库将只返回男性信息。没有用户输入直接呈现给数据库,因此我没有看到任何漏洞。