I want to populate a dropdown using jquery and ajax.
我想使用jquery和ajax填充下拉列表。
my jquery call is
我的jquery电话是
<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
statelist中的数据是
sid | statename
sid | Statename的
wb | West Bengal
wb |西孟加拉邦
ga | Goa
ga |果阿
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
我面临的问题是,当我加载页面时,我得到了预期的2个元素的下拉列表,但是以这种形式
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 个解决方案
#1
0
Jquery turns your json into an object, so you need to referene it like:
Jquery将你的json变成一个对象,所以你需要像下面那样引用它:
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.
但我猜我不是你的钥匙。如果您尝试在success参数中记录“console.log(data)”数据,您应该能够看到正确的密钥名称。
#1
0
Jquery turns your json into an object, so you need to referene it like:
Jquery将你的json变成一个对象,所以你需要像下面那样引用它:
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.
但我猜我不是你的钥匙。如果您尝试在success参数中记录“console.log(data)”数据,您应该能够看到正确的密钥名称。