django项目中如何用ajax显示搜索结果?

问题描述 投票:0回答:2

我正在一个 Django 项目中工作,其中功能之一是用户可以搜索名称(使用表单),视图将在数据库中搜索该名称(经过一些转换),结果将显示在表单下方.

目前,每次提交搜索时都需要加载整个页面。我正在应用 ajax 来使这种动态化。问题是,当我将搜索结果作为 JsonResponse 返回时,我无法在 ajax 的 success 函数中看到数据。

Views.py

def indexView (request):
    form = FriendForm ()
    friends = Friend.objects.all ()
    return render (request, "index.html", {"form": form, "friends": friends})


def searchFriend(request):
    if request.method =="POST":
        form = FriendForm (request.POST)

        if form.is_valid():
            if request.is_ajax():
                name = form.cleaned_data['name']
                query = Friend.objects.filer(first_name__contains=name)

                print(query)
                return JsonResponse(list(query), safe=False)

            else:
                return JsonResponse(form.errors)

Main.js

$(document).ready(function() {
    $("#form1").submit(function() { // catch the form's submit event
    var search = $("#searchField").val();
    

        $.ajax({ // create an AJAX call...
            data: $(this).serialize(), // get the form data
            method: 'post',
            dataType: 'json',
            url: "search/ajax/friend/",
            success: function(data) { // on success..
                console.log(data)
              
            }
        });
        return false;
    });
});
javascript python django ajax frontend
2个回答
0
投票

您的查询是否打印在终端中?

Friend.objects.filer
使用
filter
代替
filer
并使用
type: 'post'
代替
method: 'post',
并添加
data: $(search).serialize(),
而不是
data: $(this).serialize(),


0
投票
<a href="{% url 'teacher_create' %}" class="btn btn-primary">Add Teacher</a>
<input type="text" id="search-input" placeholder="Search by name">
<table class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Subjects</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody id="teacher-list">
        {% for teacher in teachers %}
            <tr>
                <td>{{ teacher.name }}</td>
                <td>{{ teacher.email }}</td>
                <td>
                </th>
                </td>
                <td>
                    <a href="{% url 'teacher_detail' teacher.pk %}" class="btn btn-sm btn-info">Details</a>
                    <a href="{% url 'teacher_update' teacher.pk %}" class="btn btn-sm btn-warning">Edit</a>
                    <a href="{% url 'teacher_delete' teacher.pk %}" class="btn btn-sm btn-danger">Delete</a>
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        $('#search-input').on('input', function () {
            var query = $(this).val();
            $.ajax({
                url: '/search_teachers/',  // URL of the AJAX endpoint
                data: { query: query },
                method: 'GET',
                success: function (data) {
                    var teacherList = $('#teacher-list');
                    teacherList.empty();
                    if (data.teachers.length > 0) {
                        $.each(data.teachers, function (index, teacher) {
                            var newRow = '<tr>' +
                                '<td>' + teacher.name + '</td>' +
                                '<td>' + teacher.email + '</td>' +
                                '<td>' + teacher.subjects + '</td>' + 
                                '<td>' +
                                '<a href="/teachers/' + teacher.pk + '/" class="btn btn-sm btn-info">Details</a>' +
                                '<a href="/teachers/' + teacher.pk + '/update/" class="btn btn-sm btn-warning">Edit</a>' +
                                '<a href="/teachers/' + teacher.pk + '/delete/" class="btn btn-sm btn-danger">Delete</a>' +
                                '</td>' +
                                '</tr>';
                            teacherList.append(newRow);
                        });
                    } else {
                        teacherList.append('<tr><td colspan="4">No teachers found for this search query.</td></tr>');
                    }
                }
            });
        });
    });
</script>


def search_teachers(request):
    query = request.GET.get('query')
    teachers = Teacher.objects.filter(name__icontains=query)
    
    teacher_data = []
    for teacher in teachers:
        subjects = ", ".join(subject.name for subject in teacher.subjects.all())
        teacher_data.append({
            'pk': teacher.pk,
            'name': teacher.name,
            'email': teacher.email,
            'subjects': subjects,
        })
    return JsonResponse({'teachers': teacher_data})
© www.soinside.com 2019 - 2024. All rights reserved.