jQuery自动完成功能不会呈现结果

时间:2018-08-28 13:08:23

标签: jquery django jquery-ui-autocomplete

试图降落!

型号:

class Student(models.Model):
    name = models.CharField(max_length=100)
    student_id = models.IntegerField()
    grade = models.IntegerField()

查看:

def student_autocomplete(request):
    query = request.GET.get('term')
    if query:
        data = (Student.objects.filter(name__startswith = query).values('name', 'student_id', 'grade'))
        return JsonResponse(list(data), safe=False)
    else:
        data='blank'
        return JsonResponse(data)

jQuery:

$(document).ready(function() {
        console.log('ready!');
    });

    $("#student_auto").autocomplete({
    source: "{% url 'student-autocomplete' %}",
    minLength: 2,
    autoFocus: true,
    select: function (event, ui) {
        $('#student_auto').val( ui.item.name );
        console.log(ui, event);
    }
    });
    $("#student_auto").removeAttr("autocomplete").attr("autocomplete", "on");

当我手动调用自动完成网址时,我可以看到数据,它看起来不错,但是结果仅显示为空框。

2 个答案:

答案 0 :(得分:0)

您需要一个成功的回调函数,然后将每个列表项映射到您的选择项,如下所示:

     $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            data: { term: request.term },
            success: function (data) {
                response($.map(data, function (i) {
                    return { label: i, value: i };
                }))
            }
        })

答案 1 :(得分:0)

别傻眼-阅读docs

  

具有标签和值属性的对象数组:[{标签:“ Choice1”,值:“ value1”},...]

哪个会导致:

def student_autocomplete(request):
    query = request.GET.get('term')
    results = []
    if query:
        data = Student.objects.filter(name__startswith = query).values()
        for d in data:
            d_json = {}
            d_json['value'] = d['name']
            d_json['id'] = d['student_id']
            results.append(d_json)
        return JsonResponse(results, safe=False)
    else:
        data ='blank'
    return JsonResponse(data)

对于陷入困境的其他人:您要自动完成的值应该标记为值。您可以通过ui.item调用其他任何值。