我正在使用jQuery插件自动完成 https://goodies.pixabay.com/jquery/auto-complete/demo.html,我正在尝试使用他们的ajax请求,不幸的是我遇到了错误。
它说
item.replace 不是 object.renderItem 的函数
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};
这是我的代码
$('.to_msg').autoComplete({
source: function(term, response){
$.getJSON('ajax/auto_complete_ajax.php', { q: term },
function(data){
response(data);
});
}
});
和我的PHP响应
$recipient = $_GET['q'];
$a_json = array();
$a_json_row = array();
//restrict the store
$query_filter = $db->query("SELECT * from master_data.user_account where Name like '%$recipient%'");
while($result_filter = $query_filter->whileFetch()){
$name = htmlentities(stripcslashes($result_filter['Name']));
$user_id = htmlentities(stripcslashes($result_filter['user_id']));
$a_json_row['user_id'] = $user_id;
$a_json_row['value'] = $name;
$a_json_row['label'] = $name;
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
这是 JSON 输出
[
{"user_id":"5","value":"Melde Feliciano ","label":"Melde Feliciano "},
{"user_id":"46","value":"Melanie Charlton ","label":"Melanie Charlton "}
]
renderItem(item, search)
中的item
是一个对象。尝试将item.replace()
替换为 item.label.replace()
。
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item.value + '">' + item.label.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};