我有一个 View ,我正在尝试显示来自几个不同位置的数据。我的想法是通过 Ajax 来执行此操作,因为加载此页面时我无法执行 3 或 4 个 url。
我可以使用 Django Rest Framework 将数据获取到页面,并且可以使用 ajax 请求在控制台中查看正确的数据。我只是不知道如何将该数据放入我的 html 模板中以开始显示它。通常我只会通过 View 传递上下文,但这是未知的领域。
我认为我错过了 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>
最佳答案
您应该以 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)
}
});
关于jquery - 使用 Ajax、Django 将上下文传递到模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49990320/