我可以将我的对象数组从views.py发送到ajax,也可以从ajax发送到html,这样我就可以访问html页面中的表数据。
HTML
{% for job in job_details %}
<tr>
<td>{{job.id}}</td>
<td>{{job.user_id}}</td>
<td>{{job.job_name}}</td>
<td>{{job.start_time}}</td>
<td>{{job.end_time}}</td>
<td>{{job.job_url}}</td>
<td>{{job.creation_date}}</td>
<td>{{job.status}}</td>
</tr>
{% endfor %}
My.js
$.ajax( {
//alert("in ajax");
type:"POST",
url:"/show_job_details/",
data:{"test_name":'execution details'},
success:function(objectfromtable){
我如何从views.py获取此对象。在此处使用模板在my.html页面中以表格格式显示
}
views.py
def show_job_details(request):
print "in job details"
if request.POST and request.is_ajax():
try:
# fetching user and job details
print "in job details"
user_object_array=UserDetails.objects.all().order_by('email_id')
print "---------------------"
print user_object_array
job_object_array=JobDetails.objects.all().order_by('creation_date')
print "$$$$$ job details"
print job_object_array
except IOError:
print "cant fetch data from jobdetails"
return HttpResponse(job_object_array)
else:
raise Http404
答案 0 :(得分:0)
你可以做的是让表格成为自己的模板。然后,您可以在返回render
时将其包含在其他模板中,并且还可以使用render_to_string
将其包含在json响应中。这允许您在一个地方对表格模板进行更改,但在任何地方都使用它进行更改而不是复制逻辑。
table.html
<table>
{% for job in job_details %}
<tr>
<td>{{job.id}}</td>
<td>{{job.user_id}}</td>
<td>{{job.job_name}}</td>
<td>{{job.start_time}}</td>
<td>{{job.end_time}}</td>
<td>{{job.job_url}}</td>
<td>{{job.creation_date}}</td>
<td>{{job.status}}</td>
</tr>
{% endfor %}
</table>
views.py:
import json
from django.template.loaders import render_to_string
def show_job_details(request):
# Other logic
job_object_array=JobDetails.objects.all().order_by('creation_date')
data = {'html': render_to_string('table.html'), 'job_details':job_object_array}
return HttpResponse(json.dumps(data), content_type='application/json')
您的javascript通话
$.ajax( {
type:"POST",
url:"/show_job_details/",
data:{"test_name":'execution details'},
success:function(response){
// Append response.html where ever you need it in your html.
console.log(response.html);
}
});