0

我在数据库的选择框中填充了状态的表单,并且必须在下面的选择框中填充基于状态选择的城市。任何人都可以帮我解决这个问题,我如何使用 codeigniter 来做到这一点。我尝试了 ajax 方式,但它不能“未定义”。

function get_city(){
var state=$("#state").val();
var dataString = 's_id='+ state;
var url="<?php echo base_url()?>admin/home/get_city";


$.ajax({
    type:"POST",
    url:url,
    data:dataString,
    success:function(data){

       $("#city").html(data);
   }
});

}

控制器:

function get_city(){


    $this->load->model('data_model');
    $data['records']=$this->data_model->get_cities();

    return $data['records'];

}

模型:

    function get_cities(){

    $this->db->select('id','city');
    $this->db->from('cities');
    $this->db->where('s_id', $this->uri->segment(4));

    $query=$this->db->get();
    if($query->num_rows()>0){
        foreach($query->result() as $row){
            $data[]=$row;

        }
        return $data;
    }
}

我需要帮助

4

2 回答 2

0

实际上,您最好将 JSON 用于此类事情:

行动:

function get_cities() {
    // Load your model.
    $this->load->model('data_model');
    // Get the data.
    $cities = $this->data_model->get_cities();
    // Specify that we're returning JSON.
    header('content-type: application/json');
    // Return a JSON string with the cities in.
    return json_encode(array('Cities' => $cities));
}

Javascript:

$('#state').change(function()) {
    // Get an instance of the select, and it's value.
    var state = $(this),
        stateID = state.val();
    // Add if statement to check if the new state id
    // is different to the last to prevent loading the same
    // data again.

    // Do the Ajax request.
    $.ajax({
        url : '/path/to/get_cities', // Where to.
        dataType : 'json', // Return type.
        success : function(data) { // Success :)
            // Ensure we have data first.
            if(data && data.Cities) {
                // Remove all existing options first.
                state.find('option').remove();
                // Loop through each city in the returned array.
                for(var i = 0; i <= data.Cities.length; i++) {
                    // Add the city option.
                    state.append($('option').attr({
                        value : data.Cities[i].value
                    }).text(data.Cities[i].city));
                }
            }
        },
        error : function() {
            // Do something when an error happens?
        }
    });
});

上面的代码将简单地返回城市列表,作为一个 JSON 对象,即

{Cities:[{id:1,city:'London'},{id:2,city:'Paris'}]}

当 jQuery 获取它时,它将把它转换回一个数组,然后您可以通过data.Cities[0].citywhere data 是 jQuery 成功回调返回的对象来访问它。

您“可以”将城市预处理为 HTML 并将其返回,但是不能在其他地方重用,因此最好通过返回 JSON 使其可移植。

希望这可以帮助 :)

于 2013-06-07T13:44:35.417 回答
0

控制器

function get_city(){

    $this->load->model('data_model');
    $records = $this->data_model->get_cities();
    $city_html = '';
    foreach ($records as $row) {
     $city_html .= '<option value="'. $row['id'] .'">'. $row['city'] .'</option>'; 
    }
    echo $city_html;
    exit;

}
于 2013-06-07T10:20:34.807 回答