我通过AJAX获得两个日期,开始和结束日期。我处理这两个日期的数据,生成一个报告,然后返回一个HttpResponse。PDF报告现在保存在我的主项目目录中。现在我得到了AJAX的回复。所以,现在我应该如何处理success函数中的响应,从服务器发回并打开一个PDF文件。
谢谢。
jQuery
$(function() {
$("#report_submit").click(function(){
$.ajax({
type : "POST",
url: "/reports/",
data : { 'start_date' : $("#startDate").val() , 'end_date' : $("#endDate").val() },
success : function(result){
},
error : function(result){
}
});
});
});
Django视图代码
def generate_report(request):
ctx = {}
if request.is_ajax():
if request.POST.has_key('start_date'):
start_date = datetime.strptime(request.POST[ 'start_date'] , '%m/%d/%Y')
end_date = datetime.strptime(request.POST[ 'end_date'] , '%m/%d/%Y')
......
# PDF GENERATED in MAIN PROJECT DIRECTORY
with open(os.path.join(os.path.dirname(__file__),'../../../../gui','Report.pdf')) as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'inline;filename=Report.pdf'
return response # so, now when I send a response back, how should I process it in AJAX success function?
pdf.closed
return render(request, 'generate_report/reports.html', ctx)
这个问题已经在下面的问题中讨论过了。。。您可能需要使用jquery插件下载文件,请不要忘记在响应中设置cookie。
PDF file download through XHR Request
您可能需要为文件下载添加一个javascript文件,并使用以下代码生成对服务器的请求。
在服务器端,当在响应中添加头等时,在响应对象中执行以下操作。i、 e
我希望你能解决这个问题,也能帮助别人。”悬垂指针“
最简单的解决方案是在“success”回调中调用
window.open(pdf_url)
,其中pdf-url是生成的pdf报告(需要传递给response)的链接。不要试图在Ajax响应中发送它。相反,让您的视图为PDF生成一个唯一的URL,然后让JS将浏览器重定向到该URL:
视图:
JS公司:
相关问题 更多 >
编程相关推荐