【问题标题】:Django Ajax Call and response with RenderDjango Ajax 调用和响应与渲染
【发布时间】:2021-03-24 06:16:42
【问题描述】:

我是 Python 和 Django 的新手,我想做一个用户有 2 个下拉菜单的任务。项目下拉和机器下拉。机器下拉菜单根据项目下拉菜单的选择填充,同时根据 2 个下拉菜单的选择刷新表格。

我正在考虑这样做,从 JavaScript 的 onChange of Item 下拉菜单中,我使用 AJAX 函数调用 view.py 中的函数,提供项目选择,如 Javascript 部分所示。在返回 Django 函数时,我使用渲染返回。

JavaScript 和 def load_machines 似乎都可以正常工作,但 return render(request, 'home.html', {'machines': machines}) 正在调用 home.html 但机器是空的.

我该如何解决这样的问题,有什么提示吗?

JavaScript 部分

<script>
    $("#exampleFormControlSelect1").change(function () {
    const url = $("#mainForm").attr("data-machines-url");
    const itemId = $(this).val();
    $.ajax({                       // initialize an AJAX request
            url: url,              
            data: {
                'itemId': itemId      // add the item id to the GET parameters
            },
            success: function (data) {   // `data` is the return of the `load_cities` view function
                
            }
        });
    });
</script>

Django 部分 视图.py

def load_machines(request):
    item = request.GET.get('itemId')
    machines = List.objects.filter(item=item).all()
    print(machines)  // working FINE
    return render(request, 'home.html', {'machines': machines})
    

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name ='home'),
    path('ajax/load-machines/', views.load_machines, name='ajax_load_machines')
    # AJAX
]

【问题讨论】:

    标签: python django


    【解决方案1】:

    而不是使用render

    return render(request, 'home.html', {'machines': machines})
    

    你应该返回JsonResponse

    from django.http import JsonResponse
    
    
    data = {'machines': machines}
    
    return JsonResponse(data)
    
    

    doc about JsonResponse is here。您还可以查看一些简单的教程,例如this

    【讨论】:

      猜你喜欢
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2017-07-13
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      相关资源
      最近更新 更多