【问题标题】:How to parse json data based on dynamic id with jquery in codeigniter如何在codeigniter中使用jquery根据动态id解析json数据
【发布时间】:2015-07-25 06:40:01
【问题描述】:

我需要从下拉列表中获取所选国家 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 的数据。我是新手,请指导

【问题讨论】:

    标签: jquery json codeigniter


    【解决方案1】:

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

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

    【讨论】:

    • 我这样做了:` $result = array() ; foreach($rawdata as $item){ if($item->id == $cId) array_push($result, $item) ; } print_r($result);退出;` 但它什么也没打印
    • 你没有json所以
    • 我认为你可以从 Ajax 函数中得到一个错误...你选择了数据类型 json
    猜你喜欢
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2012-02-15
    • 2011-06-03
    • 1970-01-01
    相关资源
    最近更新 更多