问题
I want to populate a dropdown using jquery and ajax.
my jquery call is
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "<?=base_url()?>user/getstate/", //the script to call to get data
data:'', //you can insert url argumnets here to pass to api.php
dataType: 'json', //data format
success: function(data){ //on recieve of reply
$("#state").append('<option selected>State</option>');
for(i in data)
$("#state").append("<option value=\""+data[i][0]+"\">"+data[i][1]+"</option>");
}
});
});
</script>
the part that needs to be populated is
<select id="state" class="span2" style="height:30px" name="state" required>
</select>
the function in the controller is
public function getstate(){
$this->load->model('usermodel');
$data=$this->usermodel->getstate();
echo json_encode($data);
}
the model from which the data is being fetched is
public function getstate(){
$sql="SELECT * FROM statelist";
$query=$this->db->query($sql);
$result=$query->result_array();
return $result;
}
the datas in statelist are
sid | statename
wb | West Bengal
ga | Goa
The problem i am facing is that when I load the page I get the dropdown with 2 elements as expected but in this form
State
undefined
undefined
Now i don't understand why am i getting "undefined" instead of the required or expected data like
State
West Bengal
Goa
A solution will really help me.
回答1:
Jquery turns your json into an object, so you need to referene it like:
data.i
not
data[i]
like you would with an array.
But im guessing that i is not your key. If you try and log data "console.log(data)" in success parameter, you should be able to see the correct key names.
来源:https://stackoverflow.com/questions/15852664/dropdown-population-using-jquery-to-get-data-from-codeigniter-controller