如何从控制器获取数据时迭代JSON对象

问题描述 投票:0回答:2

我想在codeigniter中创建一个依赖的下拉列表,但我不知道如何从Json获取值并在视图中显示结果

视图

<select id='countries_id' name="countries_id" onChange="getState(this.value);">
   <option>-- Select countries --</option>
   <?php foreach ($query->result() as $countries) { ?>
       <option value="<?= $countries->id ?>"><?= $countries->name ?></option>
   <?php } ?>
</select>

<select id='cities' name="city">
    <option>-- Select deparment --</option>
</select>

脚本

    <script>
        function getState(val) {
            $.ajax({
                type: "POST",
                url: "<?= base_url()?>frontend/dependantdropdown/" + val,
                data: 'countries_id=' + val,
                success: function (data) {

                    console.log(data)
                    // $("#cities").html(data);
                }
            });
        }
    </script>

调节器

public function dependantdropdown($id)
{
    $this->db->select('*');
    $this->db->from('cities');
    $this->db->where('country_id', $id);
    $data = $this->db->get();

    echo json_encode($data);
}

控制台上的响应

{
    'conn_id': {
        'affected_rows': null,
        'client_info': null,
        'client_version': null,
        'connect_errno': null,
        'connect_error': null,
        'errno': null,
        'error': null,
        'error_list': null,
        'field_count': null,
        'host_info': null,
        'info': null,
        'insert_id': null,
        'server_info': null,
        'server_version': null,
        'stat': null,
        'sqlstate': null,
        'protocol_version': null,
        'thread_id': null,
        'warning_count': null
    },
    'result_id': {
        'current_field': null,
        'field_count': null,
        'lengths': null,
        'num_rows': null,
        'type': null
    },
    'result_array': [
    ],
    'result_object': [
    ],
    'custom_result_object': [
    ],
    'current_row': 0,
    'num_rows': 0,
    'row_data': null
}

这段代码工作正常它击中控制器并在console.log中显示结果,但问题是如何获得此变量$data并迭代它并显示城市下拉列表中的结果

javascript jquery codeigniter
2个回答
0
投票

如果$data是一个类似的数组如下:

[
    ['id' => 1, 'name' => 'London'],
    ['id' => 2, 'name' => 'Paris'],
    ['id' => 3, 'name' => 'Singapore'],
    ['id' => 4, 'name' => 'New York'],
    ['id' => 5, 'name' => 'Istanbul'],
]

您可以使用以下作为您的ajax成功:

success: function (data) {
    var o = $("#cities");

    o.children(":gt(0)").remove(); // Remove all previous <option>, excluding the first "-- Select deparment --"

    $.each(data, function(k, obj) {
        o.append($("<option/>", {value: obj.id, text: obj.name}))
    });
}

0
投票

很难解释所有。但希望这可以帮助您解决问题

public function dependantdropdown($id)
{
    $this->db->select('*');
    $this->db->from('cities');
    $this->db->where('country_id', $id);
    $data = $this->db->get()->result_array();//as array

    echo json_encode($data);
}

现在你的javascript

function getState(val) {
    $.ajax({
            type: "POST",
            datatype: "JSON",//use datatype
            url: "<?= base_url()?>frontend/dependantdropdown/" + val,
            data: 'countries_id=' + val,
            success: function (data) {            
                var cities=JSON.parse(data);//convert it javascript array                   
                //now you can loop two ways
                //option 1.
                 $.each(cities, function(index,city) {
                    console.log(city['country_id']);
                    //use it as you like              
                });
                //or option 2.
                for(var i=0;i< cities.length;i++)
                {
                    console.log(cities[i]['country_id']);
                }
            }
        });
    }
© www.soinside.com 2019 - 2024. All rights reserved.