我正在使用带有codeigniter框架的jQuery自动完成功能。
这目前100%有效。
我的模特是:
function get_sku_code($q){
$this->db->select('ProductCode');
$this->db->like('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductCode'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
我的浏览javascript是:
$("#product").autocomplete(
{
source: "get_sku_codes",
messages:
{
noResults: '',
results: function() {}
},
select: function( event, ui )
{
var selectedObj = ui.item;
$.post('get_sku_prices', {data:selectedObj.value},function(result) {
$("#product").parent().parent().find('input[id^="price"]').val(result[0]);
$("#product").parent().parent().find('input[id^="adjustedprice"]').val(result[0]);
});
}
});
如上所述,这100%有效。我遇到的一个问题是,如果没有数据库匹配,则自动完成列表只是空白。有没有办法在数据库中返回“没有匹配项”'当模型没有返回值时?我应该使用jquery还是使用codeigniter mysql请求执行此操作?
一如既往地谢谢,
控制器 - get_sku_codes
function get_sku_codes(){
$this->load->model('Sales_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->Sales_model->get_sku_code($q);
}
}
答案 0 :(得分:0)
首先,根据MVC模式,您不应回显模型中的任何内容。所有这些逻辑必须位于Controller将从中获取数据的控制器。
将您的模型更改为:
function get_sku_code($q){
$this->db->select('ProductCode');
$this->db->like('ProductCode', $q);
$query = $this->db->get('ProductList');
$row_set = array();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductCode'])); //build an array
}
return $row_set;
}
你的控制器:
function get_sku_codes(){
$this->load->model('Sales_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$output = $this->Sales_model->get_sku_code($q);
$this->output->set_content_type('application/json')->set_output(json_encode($output));
}
}
然后在您的视图中,您可以在<span id="noMatches"></span>
下方或旁边的某处创建<input id="product">
元素,以便在返回结果为空时显示“无匹配”消息。
$("#product").autocomplete(
{
source: "get_sku_codes",
response: function(event, ui) {
if (ui.content.length === 0) {
$("#noMatches").html("No matches");
} else {
$("#noMatches").empty();
}
},
select: function( event, ui )
{
var selectedObj = ui.item;
$.post('get_sku_prices', {data:selectedObj.value},function(result) {
$("#product").parent().parent().find('input[id^="price"]').val(result[0]);
$("#product").parent().parent().find('input[id^="adjustedprice"]').val(result[0]);
});
}
});