如何显示jQuery自动完成响应并选择它

How to display the jQuery Autocomplete response and select it?

本文关键字:响应 选择 何显示 显示 jQuery      更新时间:2023-11-29

我希望你能帮我。我正在我的搜索表单中创建一个Ajax自动完成。我可以获得响应数组。但是我很难在UI中显示它。我只能得到"未定义"这个词。我想要的是执行Ajax自动完成,然后用户可以从建议中进行选择。

这是我迄今为止的代码。

$("#search-shop-input").autocomplete({
    source: function(request, response) {
         $.ajax({
            url: 'index.php?route=seller/seller/getSellerNames',
            dataType: 'json',
            type: 'post',
            data: { keyword: request },
            success: function(data) {
                var d = '';
                $.each(data.shops, function(key,value) {
                   $.each(value, function(k,v) {
                        console.log(k + ":" + v); //want to get username only
                   });
                });
                //response(d);
            }
        });
    },
    select: function(event, ui) {
        $("#seller_list").val(ui.item.label);
        return false;
    },
    autoFocus: true,
    min_length: 0
});

样本输出:

shops: [{user_id: "162", username: "F_Francium_1"}, {user_id: "163", username: "F_Francium_2"},…]

您首先要遍历shops数组中的每个JSON对象,因此这意味着您应该可以使用回调函数中的"this"关键字访问每个对象的属性。尝试-

$.each(data.shops, function() {
    console.log(this.username);
} 

或者如果您要将回调方法与索引和对象值一起使用。

$.each(data.shops, function (index, object) {
    console.log(object.username);
});