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].city、data が jQuery 成功コールバックによって返されるオブジェクトである場所を介してアクセスできます。

都市を HTML に前処理して返すことはできますが、他の場所で再利用することはできないため、JSON を返すことで移植可能にすることをお勧めします。

お役に立てれば :)

于 2013-06-07T13:44:35.417 に答える