dth20986 2011-01-20 16:58
浏览 38
已采纳

使用ajax和PHP过滤下拉菜单

I have a CodeIgniter MVC application.

I have a model called city that has a method:

<?php
class Cities_model extends Model{    

function Cities_model(){
    parent::Model();
}

function get_cities($id = null){
    $this->db->select('id, city_name');

    if($id != NULL){
        $this->db->where('country_id', $id);
    }

    $query = $this->db->get('cities');

    $cities = array();

    if($query->result()){
        foreach ($query->result() as $city) {
            $cities[$city->id] = $city->city_name;
        }
        return $cities;
    }else{
        return FALSE;
    }  
}
...

Controller:

function Post(){
    $this->load->helper('form');
    $this->load->model('cities_model');
    $this->load->model('country_model');
    $this->load->model('field_model');

    $data['cities'] = $this->cities_model->get_cities();//optional $id parameter 
    $data['countries'] = $this->country_model->get_countries();

    $data['fields'] = $this->field_model->get_fields(); //subject field

    $this->load->view('post_view',$data);
}

This method is used to fill the contents of a dropdown list. I have a similar model for countries, which also has a dropdown.

You can see that the get_cities method is set up to accept a country_id. This would be used to filter the results if a country was selected.

My question is I need help calling this method using Ajax (preferably jQuery). I'm new to ajax and have never done anything like this before.

Any help most appreciated!

Billy

UPDATE

I've added jquery library and have created method in my controller:

function get_cities($country){
    header('Content-Type: application/x-json; charset=utf-8');
    echo(json_encode(array($this->cities_model->get_cities($country))));
}

here is my javascript on my view:

<script type="text/javascript">

  $(document).ready(function(){

  $('#country').change(function(){
    var country_id = $('#country').val();  // here we are taking country id of the selected one.
    $.ajax({
     type: "POST",
     url: "<?php echo base_url(); ?>home/get_cities/"+country_id,
     data: ({country : country_id}),
     success: function(cities){
       $.each(cities,function(i,city)
       {
          var opt = $('<option />');
          opt.val(city.value);
          opt.text(city.text);
          $('#cities').append(opt);
       });
    }

  });

  });
  });

This is the json reply:

[{"2":"Accra"}]

So it is successfully retriving the correct data. the only problem is it's adding blank values/text to the drop down. and each time I change the city the data is being added on, so I guess i'd have to clear the dropdown first?

  • 写回答

2条回答 默认 最新

  • dongshui9690 2011-01-20 19:20
    关注

    extending Alpesh's answer:

    you should have a controller's function which return cities filtered by country:

    /controller/get_cities/<country>
    

    i'm assuming that your controller's function will return a json object, you can obtain it by doing:

    function get_cities($country)
    {
       header('Content-Type: application/x-json; charset=utf-8');
       echo(json_encode(array($this->cities_model->get_cities($country))));
    }
    

    then on the view you'll have 2 select boxes:

    1. one filled up with the contries
    2. one empty and to be filled up with the cities retrived via ajax

    now, you have to write something like Alpesh did in order to retrive the cities of the selected country; URL will be

    url: '/controller/get_cities/'+country_id
    

    while the success function would be something like

    success: function(cities)
    {
       $('#cities').empty();
       $.each(cities,function(i,city)
       {
          var opt = $('<option />');
          opt.val(city.value);
          opt.text(city.text);
          $('#cities').append(opt);
       });
    }
    

    UPDATE in your ajax success function you are dealing with a json objects, infact you are doing this:

    opt.val(city.value);
    opt.text(city.text);
    

    where city is a json object and value and text are its properties.

    when you generate the json via php you have to respect what you use in jquery so your model should return an array like this:

    array
    (
       array("value"=>"2","text"=>"Accra"),
       array("value"=>"3","text"=>"Kumasi"),
       ....
    );
    

    the json_encode that array and it should work. Maybe you don't need to wrap the model call into an array but i'm not sure depens on how you return the array

    echo(json_encode(array($this->cities_model->get_cities($country))));
    

    or

    echo(json_encode($this->cities_model->get_cities($country)));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线