我想在我的选择框中检索此json,这是我的控制器代码,

public function getDistrictById()
        {
                $StateId=$this->input->post('StateId');
                $District=$this->Main_model->getDistrictListByStateId($StateId);
                //echo json_encode($District);
                foreach($District as $d)
                {

                     $rows[]=array("id"=>$d->DistrictId,"name"=>$d->DistrictName);
                }
                print json_encode($rows);

        }


这是我的jQuery / Ajax代码

<script>
function getDistrict()
 {
        var StateId=$('#state option:selected').val();
        $.ajax({
                           url:'<?php echo base_url()?>Home/getDistrictById',
                           type: 'POST',
                          dataType:"json",
                           data: {StateId:StateId},
                           success: function(response){
                            // $('#District').html(response);
                            console.log(response);
                           },

                           error: function(){
                               alert("Fail");
                           }
                       });
 }
</script>


console.log(response);给我确切的输出,但我不确定如何将其附加到选择框。我已经尝试过How do I add options to a DropDownList using jQuery?和更多PLZ帮助...

最佳答案

在成功回调中就这样做

    <script>
    function getDistrict()
                            {
                                var StateId = $('#state option:selected').val();
                                $.ajax({
                                    url: '<?php echo base_url()?>Home/getDistrictById',
                                    type: 'POST',
                                    dataType: "json",
                                    data: {StateId: StateId},
                                    success: function (response) {
                                       $("#district").empty();  // clear previous options
                                        for (i = 0; i < response.length; i++)
                                        {
                                            $("#district").append("<option value='" + response[i].id + "'>" + response[i].name + "</option>");
                                        }
                                    },
                                    error: function () {
                                        alert("Fail");
                                    }
                                });
                            }
       </script>

10-08 15:25