如何将选择数组从ajax传递到codeigniter视图?

时间:2014-12-03 03:21:23

标签: php jquery ajax codeigniter

我找到了最佳答案here,但是当我在代码中实现它时,下拉选择选项会发生以下情况:


1



Ť
Ë
小号
Ť
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']));
}

1 个答案:

答案 0 :(得分:1)

这是因为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));
    });
}