php - 未捕获的类型错误。 Item.replace 不是函数,autoComplete 插件

标签 php jquery json ajax autocomplete

我正在使用 jQuery 插件 autoComplete https://goodies.pixabay.com/jquery/auto-complete/demo.html ,我正在尝试使用他们的 ajax 请求,不幸的是我遇到了错误。

上面写着

item.replace is not a function at 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){}
};

关于php - 未捕获的类型错误。 Item.replace 不是函数,autoComplete 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42195498/

相关文章:

javascript - 当内容溢出超过div的固定高度时如何创建新的div?

jQuery:分层选项卡用户界面

php - 没有数据怎么选NULL,有数据就显示?

PHP 变量不打印到 HTML 网页

php - Yii email 的验证器到底验证了什么?

javascript - 正则表达式未返回预期的匹配项

java - 如何从 MySQL 获取所需格式的 JSON

javascript - Protractor 中的 Json 断言

php - 如何在 laravel 中获取列值的平均值

php - 1 周的每日平均值