如何将选择数组从ajax传递给codeigniter视图?
问题描述:
我找到了最好的答案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']));
}
答
这是因为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));
});
}
LOCS不是有效的JSON – 2014-12-03 03:30:51
,如果它是有效的警报会显示'[Object对象]'不是字符串 – 2014-12-03 03:40:16