2014-12-03 108 views
0

我找到了最好的答案here,但是当我在我的代码来实现它,这里就是发生在下拉列表中选择选项:如何将选择数组从ajax传递给codeigniter视图?





牛逼
Ë
小号



(依此类推)。

它有什么问题?

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'])); 
} 
+0

LOCS不是有效的JSON – 2014-12-03 03:30:51

+2

,如果它是有效的警报会显示'[Object对象]'不是字符串 – 2014-12-03 03:40:16

回答

1

这是因为locs被解析为一个字符串,但不是一个JSON对象。 尽量把数据类型在$阿贾克斯这样的:

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

谢谢你,所以它工作! – Marsha 2014-12-03 07:45:45

+0

很高兴我能帮助,欢呼! – kyo 2014-12-03 11:14:05

相关问题