Jquery自动完成不显示结果框

时间:2014-01-22 12:33:38

标签: jquery autocomplete

我有这个js脚本:

$('#other_teacher').autocomplete({
    source: function (request, response) {
        $.ajax({
            url: '/app_dev.php/en/teacher/ajax/courseadd-teacher/'+request.term,
            type: 'GET',
            dataatType: 'json',
            success: function(data) {
                console.log(data);
                response($.each(data, function(index, value) {
                    return {
                        label: value,
                        value: index
                    }
                }));
            }
        });
    },
    minLength: 1
});

ajax请求的结果是:

[{"id":2,"name":"Moran bob"},{"id":2,"name":"Willam Lawsan"}]

Ajax resquest start,数据有结果对象,但不显示结果窗口。

2 个答案:

答案 0 :(得分:1)

使用$.map代替$.each,然后从对象中访问字段的值。 我还在里面添加了一个select函数和一个logger来确认你是否真的得到了什么

$('#other_teacher').autocomplete({
    source: function (request, response) {
        $.ajax({
            url: '/app_dev.php/en/teacher/ajax/courseadd-teacher/'+request.term,
            type: 'GET',
            dataatType: 'json',
            success: function(data) {
                console.log(data);
                response($.map(data, function(item) {
                    return {
                        label: item.id, // or item.name if you want
                        value: item.name
                    }
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        console.log(ui.item);
    }
});

答案 1 :(得分:0)

将Css用于自动完成,然后尝试此代码

   $('#textbox id').autocomplete({
        source: function (request, response) {
            $.getJSON("url?term=" + request.term, function (data) {
                response(data);

            });

        },
        minLength: 1,
        delay: 100

    });