这是我的模特. get items将根据位置从数据库中获取项目名称
class Itemsale_db extends CI_Model
public function getItems($userid,$loc)
{
$sql = "SELECT DISTINCT Name from itransfile where";
if (is_numeric($loc))
$sql .= " location_id = ".$loc;
else
$sql .= " location_id IN(SELECT location_id FROM client_locations where client_id = " .$userid. ")";
$query = $this->db->query($sql);
$item = $query->result_array();
return $item;
}
}
这是我的控制器. getItemsAjax将调用模型并返回json编码的数组进行查看.
class ItemSale extends CI_Controller {
public function getItemsAjax($userid,$locid)
{
$this->load->model('itemsale_db');
header('Content-Type: application/x-json; charset=utf-8');
$item = $this->itemsale_db->getItems($userid,$locid);
echo json_encode($item);
}
}
这是Javascript. loc是位置选择框,items是项目选择框
$(document).ready(function(){
$('#loc').change(function(){
$("#items > option").remove();
var opt = $('<option />');
opt.val('All');
opt.text('All');
$('#items').append(opt);
var loc_id = $('#loc').val();
var userid = "<?php echo $this->session->userdata('userid'); ?>";
$.ajax({
type: "POST",
url: "<?php echo base_url()?>" + "index.php/itemsale/getItemsAjax/"+loc_id + "/"+userid,
success: function(item)
{
$.each(item,function(Name)
{
var opt = $('<option />');
opt.val(Name);
opt.text(Name);
$('#items').append(opt);
});
}
});
});
});
Ajax调用返回我的整数列表而不是项目名称.
执行console.log(项目)
解决方法:
您的代码问题是这($.each函数的格式不正确).
First argument should be index and second should be value in $.each
callback.
这是$.each回调函数的正确格式(Integer indexInArray,Object value)
在ajax成功中使用以下代码:
$.each(item,function(index,Name) {//added index first and then value
var opt = $('<option />');
opt.val(Name);
opt.text(Name);
$('#items').append(opt);
});
注意:当您在每个回调中仅使用单个参数时,它会处理名称广告索引.