如何将选择选项数组从 ajax 传递到代码点火器视图


How to pass select option array from ajax to codeigniter view?

我在这里找到了最好的答案,但是当我在代码中实现它时,下拉选择选项会发生什么:

"

1"

"
t
e
s
t

1"

(等等)。

怎么了?

视图中的 ajax 代码:

$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/main/get_location",
data: data_loc,
success: function(locs)
{
    //alert(locs); when I do this, the alert shows: {"1": "test 1", "2": "test 2"}.
    $('#location').empty();
    $('#location').show();
    $.each(locs,function(id,location_description){
        $('#location').append($("<option></option>").attr("value",id).text(location_description));
    });
}

});

在控制器中:

public function get_location()
{
    $this->load->model("xms/model_db"); 
    echo json_encode($this->model_db->get_location_by_group($_POST['location_gr']));
}

这是因为locs被解析为字符串而不是 json 对象。尝试将数据类型放入 $.ajax 中,如下所示:

$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/main/get_location",
data: data_loc,
dataType: 'json',
success: function(locs, dataType)
{
    $('#location').empty();
    $('#location').show();
    $.each(locs,function(id,location_description){
        $('#location').append($("<option></option>").attr("value",id).text(location_description));
    });
}

或者也许使用 parseJSON:

$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/main/get_location",
data: data_loc,
success: function(result)
{
    loc = $.parseJSON(result);
    $('#location').empty();
    $('#location').show();
    $.each(locs,function(id,location_description){
        $('#location').append($("<option></option>").attr("value",id).text(location_description));
    });
}