我有一种观点,我试图从几个不同的地方显示数据。我的想法是通过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>
答案 0 :(得分:3)
您应该将您的回复作为Json对象
返回from django.http import JsonResponse
data = {
'historical_loads': historical_loads,
'historical_carriers': historical_carriers
}
return JsonResponse(data)
jquery 第一个选项(不需要循环django):
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)
}
});
答案 1 :(得分:0)
这是一个例子: 的视图强>
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%}
mor关于ajax here Ajax doc