我通过 AJAX 获得 2 个日期,开始日期和结束日期。我处理这两个日期的数据,生成报告,然后返回一个 HttpResponse。 PDF 报告现在保存在我的主项目目录中。现在我在 AJAX 中得到回复。那么,现在我应该如何处理成功函数中的响应,从服务器发回并打开 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)
最佳答案
不要尝试在 Ajax 响应中发送它。相反,让您的 View 为 PDF 生成一个唯一的 URL,然后让 JS 将浏览器重定向到该 URL:
查看:
return HttpResponse(json.dumps({'url': my_url})
JS:
$.ajax({
type : "POST",
dataType: "json",
url: "/reports/",
data : { 'start_date' : $("#startDate").val() , 'end_date' : $("#endDate").val() },
success : function(result){
var url = result['url'];
window.location = url;
},
关于python - 如何在 AJAX 请求成功响应中返回文件时打开 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20466864/