当我搜索用户名“ a”时,它仅获取前5个用户名并显示“正在加载更多结果……”,但未加载,当我对其进行调试时,page参数未增加,它仅停留1,其中术语参数工作正常。 下面是我的代码:
function getCommonAutoComplete(urlStr) {
$(".item-dropdown").select2({
placeholder: "[Select Item]",
allowClear: true,
ajax: {
url: urlStr,
dataType: "json",
delay: 250,
casesensitive: false,
data: function(params) {
return {
q: params.term, // search term
page: params.page || 1
};
},
processResults: function(data, params) {
var resData = [];
data.forEach(function(value) {
resData.push(value);
});
var page = params.page || 1;
return {
results: $.map(resData, function(item) {
return {
text: "[" + item.item_code + "] " + item.ItemName,
id: item.id
};
}),
pagination: {
more: page * 5 <= data[0].total_count
}
};
},
cache: true
},
minimumInputLength: 1
});
}
下面是我的服务器端代码,它是控制器
public function actionSearchItem(){
$string=$_GET['q'];
$page= $_GET['page'];
$data=$this->fin->getItemAjax($string,$page);
echo CJSON::encode($data);exit;
}
这是我的模特
public function getItemAjax($string,$page){
$resultCount = 5;
$end = ($page - 1) * $resultCount;
$start = $end + $resultCount;
$sql="SELECT item_name as ItemName,item_code,id from wp_item where item_name like '%$string%' LIMIT {$end},{$start}";
$result = Yii::app()->db->createCommand($sql)->queryAll();
foreach ($result as $itemKey => $ajaxValue) {
$data[] = ['id'=>$ajaxValue['id'], 'ItemName'=>$ajaxValue['ItemName'],'item_code'=>$ajaxValue['item_code'], 'total_count'=>count($result)];
}
return $data;
}
这是我的Json数据
[
{ id: "2", name: "Tracy Moen DVM", total_count: 5 },
{ id: "3", name: "Miss Zena Swift Jr.", total_count: 5 },
{ id: "4", name: "Gail Kunde", total_count: 5 },
{ id: "5", name: "Edna Langworth", total_count: 5 },
{ id: "7", name: "Meta Weimann", total_count: 5 }
];
答案 0 :(得分:0)
您正在以错误的方式处理分页-这不是“开始”和“结束”,而是“限制”和“偏移”。此外,total_count
的计算方式有误,您查询的数据库容易受到SQL注入的攻击。您应该尝试这样的事情:
public function getItemAjax($string, $page) {
$resultCount = 5;
$offset = ($page - 1) * $resultCount;
$limit = $resultCount;
$sql = "SELECT item_name as ItemName, item_code, id from wp_item where item_name like '%:string%' LIMIT {$offset}, {$limit}";
$result = Yii::app()->db->createCommand($sql)->queryAll(true, ['string' => $string]);
$countSql = "SELECT count(*) from wp_item where item_name like '%:string%'"
$totalCount = Yii::app()->db->createCommand($countSql)->queryScalar(['string' => $string]);
foreach ($result as $itemKey => $ajaxValue) {
$data[] = [
'id' => $ajaxValue['id'],
'ItemName' => $ajaxValue['ItemName'],
'item_code' => $ajaxValue['item_code'],
'total_count' => $totalCount,
];
}
return $data;
}