2014-12-03 105 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

相關問題