选择选项中的数组中的echo json数据

时间:2012-11-27 22:05:11

标签: jquery json codeigniter codeigniter-2

我正在尝试使用Json在我的代码点火器视图上删除数据。它返回

[{“id”:“5”,“cityname”:“Manegerial Estate”},{“id”:“6”,“cityname”:“Kilimani”},{“id”:“12”, “城市名”: “工匠”}]

部分代码。如何在选项选择中回显返回的对象。它回应上面选择的返回值

    var post_url = "control_form/get_cities_by_state/"+ state_id;
        $.ajax({
            url: post_url,
            type: "POST",

            // dataType: 'json',
             success: function(cities) //we're calling the response json array 'cities'
              {
                alert(cities);
                $('#f_city').empty();
                $('#f_city, #f_city_label').show();
                   $.each(cities,function(id,city) 
                   {
                    var items=cities['id'];
                    alert(items);
                    var opt = $('<option />'); // here we're creating a new select option for each group
                      opt.val(id);
                      opt.text(city);
                      $('#f_city').append(opt); 
                   });
           }); //end AJAX
       } else {
        $('#f_city').empty();
        $('#f_city, #f_city_label').hide();
    }//end if
}); //end change
});
    </script>
 </head>
<body>
    <p>
<?php echo form_open('control_form/add_all'); ?>
        <label for="f_state">State<span class="red">*</span></label>




        <select id="f_state" name="f_state" required>
            <option value="" selected=selected>--Select state--</option>
            <?php
            foreach($statename as $state):
                echo '<option value="' . $state->id . '">' . $state->statename . '</option>';
            endforeach;
            ?>

        </select>
        <label for="f_city"  id="f_city_label">City<span class="red" >*</span></label>
        <!--this will be filled based on the tree selection above-->
        <select id="f_city" name="f_city" id="f_city_label"> 
            <option value=""></option>
        </select>
        <label for="f_membername">Member Name<span class="red">*</span></label>
      <input type="text" name="f_membername"/>
<?php echo form_close(); ?>


    </p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要指定json dataType ...

$.ajax({
        url: post_url,
        type: "POST",
        dataType: "json",

然后在你的成功函数中:

$.each(cities,function(i, city) {

    var opt = $('<option />'); // here we're creating a new select option for each group
    opt.val(city.id);
    opt.text(city.cityname);
    $('#f_city').append(opt); 

});