0

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

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

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

    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>
4

1 回答 1

0

您需要指定 json 数据类型...

$.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); 

});
于 2012-11-27T22:11:27.920 回答