【问题标题】:Pass context into a template using Ajax, Django使用 Ajax、Django 将上下文传递到模板中
【发布时间】:2018-10-04 01:04:00
【问题描述】:

我有一个视图,我试图将来自几个不同位置的数据显示到其中。我的想法是通过 Ajax 执行此操作,因为当此页面加载时我无法执行 3 或 4 个 url。

我可以使用 Django Rest Framework 将数据获取到页面,并且可以使用我的 ajax 请求在控制台中查看正确的数据。我只是不知道如何将这些数据放入我的 html 模板以开始显示它。通常我只会通过视图传递上下文,但这是未知领域。

我认为我在使用 Jquery 时遗漏了一些非常小的东西,因为我对 javascript 和 Jquery 还是很陌生。

views.py

class LoadLaneHistoricalCarriers(APIView):
    authentication_classes = ()
    permission_classes = ()

    def get(self, request, pk):
        load = Load.objects.get(pk=pk)
        load_state = load.shipper.state
        load_equipment_type = load.equipment_type

        historical_loads_in_state = Load.objects.filter(shipper__state=load_state)
        carriers = CarrierCompany.objects.filter(state=load_state)

        historical_carriers = []
        historical_loads = []

        for load in historical_loads_in_state:
            historical_loads.append(load.id)
            historical_carriers.append(load.carrier.name)

        data = {
        'historical_loads': historical_loads,
        'historical_carriers': historical_carriers

        }
        return Response(data)

模板这是一个重要的模式。

<script>
  var endpoint = '/carrier_notifications/load/historical_carriers/400192/data/'
    $.ajax({
        method: "GET",
        url: endpoint,
        success: function (data) {
          carriers = data.historical_carriers
          console.log(carriers) //This works
        },
        error: function(error_data){
            console.log("error")
            console.log(error_data)
        }
      });
</script>

<table class="table table-condensed" id="historicalCarriers">
  <thead>
    <tr>
      <th>Load Number</th>

    </tr>
  </thead>
  <tbody>
    {% for carrier in carriers %}
    <tr>
      <td>
        <a href="#">{{ carrier }}</a>
      </td>
    </tr>
    {% endfor %}
  </tbody>
</table>

【问题讨论】:

  • 你能告诉我你的模态在哪个模板中吗?它是否与您的端点共享相同的模板?

标签: jquery ajax django django-rest-framework


【解决方案1】:

您应该将响应作为 Json 对象返回

from django.http import JsonResponse

data = {
    'historical_loads': historical_loads,
    'historical_carriers': historical_carriers

    }
return JsonResponse(data)

jquery 第一个选项(不需要 django for 循环):

var tbody = $("tbody")
$.ajax({
    method: "GET",
    url: endpoint,
    success: function (data) {
      carriers = data.historical_carriers
      for(var i = 0 ; i < carriers.length ; i++){
          html = '<tr><td><a href="#">'+carriers[i]+'</a></td></tr>';
          tbody.append(html)
      }
    },
    error: function(error_data){
        console.log("error")
        console.log(error_data)
    }
  });

【讨论】:

  • 太棒了!这确实产生了我需要的东西。不过,我需要对其进行调整以使其更好地适应我的用例。我显然有一些 javascript 需要学习。是否可以将数据传递给我的模板,以便我可以使用 django for 循环?我想要访问的数据还有很多。
  • 我很高兴能提供帮助。当然,在我的示例中,您有一个名称数组,但您可能也希望拥有链接,只需为您的案例格式化一个格式良好的 JSON 对象。 学习是关键
  • 没错,我能够为每个名称格式化详细链接。我会处理这个并对其进行更多调整
  • 我知道如果模态与您的端点位于同一模板中的方法。基本上,如果您处理相同模板中的数据......您的模态在哪个模板中?它是否与您的端点共享相同的模板?
  • 我想做同样的事情,除了 1 行代码,我有一个完整的 HTML 文档,它使用在 AJAX 中收到的数据。我如何做到这一点?
【解决方案2】:

这是一个例子: 观看次数

template = loader.get_template('start_interview.html')
  context = Context({ 'upload_response': 'True'})
  return HttpResponse(template.render(context))

ajax

$.ajax({
  type: "POST",
  url: "<your url to the view that returns appropriate template>",
  data: { name: "Tegito123", location: "New York" }
}).done(function( responseMsg ) {
  $('#notifier').html(responseMsg)
});

在您的模板中

{%if upload_response %}
 ...Your html tags or jquery if inside script block...
{%else%}
 ...Do Stuff if it is false...
{%endif%}

关于 ajax 的更多信息 here Ajax doc

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多