我能够成功地从控制器以json格式从数据库中获取数据,这就是它的外观:
{
"dealer":[
["1","himanshu"],
["2","bhola the dealer"],
["3","bhola the dealer"]
]
}
问题是我无法将json数据传递到控制器视图中的下拉列表中。
型号代码:
public function getName(){
$this->db->select('dealerid,dealername');
$query=$this->db->get('Dealer');
$result=$query->result_array();
//echo "<pre>";
return $result;
}
控制器代码:
public function dealer_list()
{
$list = $this->person->getName();
$ddata = array();
foreach ($list as $person) {
$row = array();
$row[] = $person['dealerid'];
$row[] = $person['dealername'];
$ddata[] = $row;
}
$output = array(
"dealer" => $ddata,
);
//output to json format
echo json_encode($output);
}
查看代码:
//get a reference to the select element
$select = $('#select');
//request the JSON data and parse into the select element
$.ajax({
url: "<?php echo site_url('dealer_controller/dealer_list')?>"
, dataType: 'JSON'
, success: function (data) {
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.dealer, function (key, val) {
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
}
, error: function () { <strong>
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
答案 0 :(得分:1)
您的json输出没有每个经销商的密钥id
或name
。因此val.id
和val.name
无效。
在您的控制器更改中:
$row[] = $person['dealerid'];
$row[] = $person['dealername'];
为:
$row["id"] = $person['dealerid'];
$row["name"] = $person['dealername'];
这会将键id
和name
添加到php数组中,当转换为json时,应输出如下内容:
{"dealer":[{"id": "1", "name": "himanshu"}, {...}]}
然后可以使用$.each
和val.id
val.name
中检索这些内容
答案 1 :(得分:0)
$.each(data.dealer, function (index, item) {
$select.append(
$('<option>', {
value: item[0],
text: item[1]
}, '</option>'))
}
)
})