【发布时间】: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