【问题标题】:PDF response to AJAX won't display不会显示对 AJAX 的 PDF 响应
【发布时间】:2014-07-24 17:51:18
【问题描述】:

我在 django 网站上使用 reportlab 来创建和返回 PDF。到目前为止,这仅限于一个“报告”页面,但我正在尝试扩展它使用的地方。我创建了一个返回正确响应的 ajax 调用,但保存/查看 PDF 的对话框从未出现,而是页面刷新。我猜这是因为我的 ajax 调用没有成功函数,但我不确定它应该是什么。

JS:

function get_report(){
  $.ajax({
    url: '{{root_url}}/timecard/',
    type: 'POST',
    data: {'emp_id':employee_id},
    dataType: 'html',
  });
}

HTML:

<input id="id_report" type="submit" value="Print" onclick="get_report()"/>

姜戈:

def view_timecard(request):
    if request.method == 'POST':
        response = get_timecard_report(request)
        return response

函数 get_timecard_report 使用预先存在的函数来构造一个响应,该响应在原始页面上显示一个对话框以打开或保存 PDF。使用调试器,返回的响应看起来与正常运行的响应相同。

我想我只需要在 ajax 成功中正确处理这个问题,但我不确定那会是什么。

【问题讨论】:

  • 我真的不明白你为什么要在这里使用 ajax。您想按下一个按钮并以 PDF 的形式获得响应:这正是普通提交按钮所做的。

标签: ajax django pdf reportlab


【解决方案1】:

看起来您正在进行 ajax 调用,但未处理响应。 你是对的,缺少成功功能。您只需要使用响应填充 HTML 元素(您可以使用“框架”或“对象”html 标签将 pdf 嵌入到 html 页面中)并处理 ajax 错误。

ajax({
 url: '{{root_url}}/timecard/',
type: 'POST',
data: {'emp_id':employee_id},
dataType: 'html', 
success: function(response){
   if (response)
        <get document elementid and set the inner html as the PDF response using javascript>
    },
error: function(xhr,status,error){

if xhr.readyState == 0 || xhr.status == 0
  return;
else
alert("xhr status:" + xhr.status); alert("in get_report function")
}
})

顺便说一句,您这里的视图代码不清楚,但您需要将 PDF 输出为附件。

类似这样的: response['Content-Disposition'] = '附件;文件名="somefilename.pdf"'

Output PDFs with django

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2016-01-28
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多