如何在codeigniter

时间:2015-07-25 06:40:02

标签: jquery json codeigniter

我需要从下拉列表中获取所选国家/地区ID的国家/地区代码

我有一个ajax调用,它返回一个json数据:

function fetchCountryCode(sel) {

    var country_id = sel;
    var data = "country_id=" + country_id
   // var baseurl =
    alert(country_id);
    $("#code").html("");
    if (country_id.length > 0) {

        $.ajax({
            type: "POST",
            url: "<?php echo base_url();?>index.php/register/code",
            data: "country_id=" + country_id,
            dataType: 'json',
            success: function(html) {
                $("#code").html(html);

            }

        });
    }

}

解析数据的控制器功能:

public function code($countryId)
{
    // Get countries list
    $cId = $_POST['country_id'];
    //echo "<pre>"; print_r($cId); exit;
    $code = file_get_contents($this->config->config['api_url'] . 'countries');
    $rawdata = json_decode($code);
   // echo "<pre>"; var_dump($rawdata);

    foreach($rawdata as $item){
        print_r($item->code);
    }
 exit;
    $data['countries'] = $this->load->view('login/code', $code);
}

它正在向我提供所有国家/地区的数据,但我只需要获取所选的ID数据。我是新手,请指导

1 个答案:

答案 0 :(得分:0)

您可以创建一个只有匹配id的数组,然后将结果作为json回显。

$result = array() ;

foreach($rowdata as item){
    if($item->id == $cId)
           array_push($result, $item) ;
} 

echo json_encode($result);