【问题标题】:Ajax not working in codeigniter to populate dropdownAjax 无法在 codeigniter 中工作以填充下拉列表
【发布时间】:2014-02-28 04:49:37
【问题描述】:

我正在尝试使用 codeigniter 中的 ajax 从下拉列表中获取城市。

我不明白出了什么问题?下面是代码:

<?
## controller ##
class Pages extends CI_Controller {
    public function __construct()
  {
       parent::__construct();
       $this->load->model('home_model');
       $this->load->model('sub_cat_model');
       $this->load->model('state_model');
       $this->load->model('city_model');
       $this->load->model('location_model');
       $this->load->library('email');
  }
public function index()
{
      $data['state'] = $this->home_model->get_state();
     $data['title'] = 'Rimi Classified - Home';

      $this->load->view('templates/header', $data);
    $this->load->view('index', $data);
    $this->load->view('templates/footer', $data);
}
 public function sign_up()
 {
 $data['states'] = $this->state_model->get_states();

 $data['error'] = '';
     $data['title'] = 'Rimi Classified - Sign up';
 $this->load->view('templates/header1', $data);
 $this->load->view('sign-up', $data);
 $this->load->view('templates/footer', $data);      
 }
public function get_cities($state){

 header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->city_model->get_cities($state)));
  }
}

> ##country model ##

class State_model extends CI_Model {

public function __construct() {
 $this -> load -> database();

}

function get_states() {
 $query = $this->db->order_by('state', 'ASC')->get('state');


$states = array();

if ($query -> result()) {
 foreach ($query->result() as $state) {
  $states[$state -> id] = $state -> state;
 }
  return $states;
 } else {
  return FALSE;
  }
 }

> ## city_model starts ##

<?php
class City_model extends CI_Model {

 public function __construct() {
  $this -> load -> database();
  //$this->output->enable_profiler(TRUE);

}
function get_cities($state = NULL){
  if($state != NULL){
      $this->db->where('state_id', $state);

     $query = $this->db->get('city');
     $cities = array();
     if($query->result())
     {
        foreach ($query->result() as $city) 
        {
        $cities[$city->id] = $city->city;
        }
              return $cities;
         }
     else
     {
        return FALSE;
     }
    }
    else
    {
        $cities[] = "-- Select City --";
        return $cities;
    }
 }
}


> ## view ##

  <div id="innerdiv1">
        <label>State</label>


$states['#'] = '-- Select State --';

echo form_dropdown('state_id', $states, '#', 'id=state_id');
?>
      </div>
      <div id="innerdiv2">
        <label>City</label>

<select name="city_id" id="city_id">
<option value="">-- Select City-- </option>
</select>
      </div>


> ## Ajax starts here ##

  <script type="text/javascript">// <![CDATA[
 $(document).ready(function(){
  var base_url = "<?=base_url()?>";
  $('#state_id').change(function(){ 
  $("#city_id > option").remove(); 
  var state = $('#state_id').val(); 

  $.ajax({
  type: "POST",
      url: base_url+"pages/get_cities/"+state, 

  success: function(cities) 
  {
      $.each(cities,function(id,city)
      {
      var opt = $('<option />'); 
      opt.val(id);
      opt.text(city);
          $('#city_id').append(opt); 
     });
 }
 });
});
 });
 // ]]>
</script>

上面是我找不到错误的代码。任何人都可以帮助我摆脱

这个问题。 csrf_protection 在配置中设置为 true。

【问题讨论】:

    标签: php jquery ajax codeigniter


    【解决方案1】:

    您应该在 javascript ajax 帖子中传递 CSRF 名称和值..

     <script>
             var csfrData = {};
             csfrData['<?php echo $this->security->get_csrf_token_name(); ?>']
                               = '<?php echo $this->security->get_csrf_hash(); ?>';
             $.ajax({
               type: "POST",
               url: base_url+"pages/get_cities/"+state, 
               data : csfrData,
               success: function(cities) 
               {
                 $.each(cities,function(id,city){
                     var opt = $('<option />'); 
                     opt.val(id);
                     opt.text(city);
                     $('#city_id').append(opt); 
                });
              }
           });
           </script>
    

    在 PHP 控制器中返回不起作用,请使用die

     header('Content-Type: application/json; charset=utf-8');
     die(json_encode($this->city_model->get_cities($state)));
    

    【讨论】:

    • 嗨 Girish 感谢您的帮助,但代码仍然无法获取城市。
    • @KaustavDey 请检查更新代码,希望对您有所帮助
    • @KaustavDey,请在 ajax success 函数中回显 console.log(cities)
    • 我在成功函数中有 alert(console.log(cities)) 它显示未定义
    • @KaustavDey, alert(console.log(cities)) ???,您应该在完成之前查看链接 [stackoverflow.com/questions/4743730/…
    【解决方案2】:

    把这个函数改成

    function get_cities($state = NULL){
      if($state != NULL){
          $this->db->where('state_id', $state);
    
         $query = $this->db->get('city');
         $cities = array();
         $html = '';
         if($query->result())
         {
            foreach ($query->result() as $city) 
            {
            $html .= '<option value="'.$city->id].'">'.$city->city.'</option>';
            }
                  return $html;
             }
         else
         {
            return FALSE;
         }
        }
        else
        {
            $html = '<option value="">--Select City--</option>';
            return $html;
        }
     }
    }
    

    【讨论】:

      【解决方案3】:

      用这个替换你的控制器功能..

      public function get_cities($state){
      
      $cities = $this->city_model->get_cities($state);
      
      $html = '';
      
      foreach ($cities as $k => $v)
      {
        $html .= "<option value=".$k.">".$v."</option>";
      }
      
      echo $html;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-16
        • 2013-09-24
        • 1970-01-01
        • 2016-10-17
        • 2012-11-08
        • 1970-01-01
        • 1970-01-01
        • 2011-07-17
        • 2012-08-12
        相关资源
        最近更新 更多