我在这个jQuery UI自动完成设置中看到了奇怪的行为。
当我开始输入说“Smith”时,自动完成功能在下拉列表中提供了几个选项(例如,“Joe Smith”,“Mary Taylor”,“Jack Sparrow”)。在控制台上,我看到没有错误,响应是
[{"value":"Joe Smith"},{"value":"Mary Taylor"},{"value":"Jack Sparrow"}]
但是,如果我点击提交/搜索按钮,那么我会得到一个空白页面:
[{"value":"Joe Smith"}]
不知何故,我的Model查询在运行jQuery自动完成时返回所有用户 - 但是当我手动触发它时,它会返回正确的结果。
知道这里有什么问题吗?
感谢。
JS:
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).attr( "scrollTop", 0 );
}
$( "#search_input" ).autocomplete({
source: "http://example.com/search",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
Controller(search.php,CodeIgniter标记):
function index()
{
$term = $this->input->post('search_input');
$response = json_encode($this->search_model->search($term));
echo $response;
}
模型(search_model.php,CodeIgniter标记):
function search($term)
{
$query = $this->db->query("
SELECT up.first_name, up.last_name
FROM user_profiles up, users u, pets p
WHERE u.activated = 1
AND u.banned = 0
AND up.last_name LIKE '%" . $term . "%'
GROUP BY up.last_name
ORDER BY up.last_name ASC;
");
$search_data = array();
foreach ($query->result() as $row) {
$search_data[] = array(
'value' => $row->first_name . ' ' . $row->last_name,
);
}
return $search_data;
}
答案 0 :(得分:1)
看起来您没有发送搜索字词。我把它简化为一个php函数。 $ term将由自动完成脚本发送。
$term = $_GET['term']
function search($term)
{
$query = $this->db->query("
SELECT up.first_name, up.last_name
FROM user_profiles up, users u, pets p
WHERE u.activated = 1
AND u.banned = 0
AND up.last_name LIKE '%" . $term . "%'
GROUP BY up.last_name
ORDER BY up.last_name ASC;
");
$search_data = array();
foreach ($query->result() as $row) {
$search_data[] = array(
'value' => $row->first_name . ' ' . $row->last_name,
);
}
echo json_encode($search_data);
}
答案 1 :(得分:0)
我认为更好的解决方案是使用jQuery .ajax()
并将函数设置为POST
数据。这样我就可以避免使用GET
,也不必创建额外的控制器来同时处理POST
和GET
。
$("#search_input").autocomplete({
source: function(request, response) {
$.ajax({
url: "search",
dataType: "json",
type: "POST",
data: {
search_input: request.term
},
success: function(data) {
//map the data into a response that will be understood by the autocomplete widget
response($.map(data, function(item) {
return {
label: item.value,
value: item.value
}
}));
}
});
},
minLength: 2,
//when you have selected something
select: function(event, ui) {
//close the drop down
this.close
},
//show the drop down
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
//close the drop down
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});