【问题标题】:How to display the jQuery Autocomplete response and select it?如何显示 jQuery 自动完成响应并选择它?
【发布时间】:2015-04-17 16:35:02
【问题描述】:

我希望你能帮助我解决这个问题。我正在我的搜索表单中创建一个 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"},…]

【问题讨论】:

    标签: javascript jquery ajax autocomplete jquery-ui-autocomplete


    【解决方案1】:

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

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

    或者,如果您使用带有索引和对象值的回调方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 2011-09-19
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多