POST 到服务器,接收 PDF,使用 jQuery 交付给用户 [英] POST to server, receive PDF, deliver to user w/ jQuery

查看:24
本文介绍了POST 到服务器,接收 PDF,使用 jQuery 交付给用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接,用户点击该链接可以获取 PDF.在 jQuery 中,我创建了一个对服务器的 POST ajax 调用以获取 PDF.PDF 带有正确的内容标题等,通常会导致浏览器打开阅读器插件,或允许用户保存 PDF.

I have a link that the user clicks to get a PDF. In jQuery, I create a POST ajax call to the server to get the PDF. The PDF comes to me with the correct content headers etc that would normally cause the browser to open the Reader plugin, or allow the user to save the PDF.

由于我通过 ajax 调用获取 PDF,因此我不确定如何处理我在 OnSuccess 回调中获取的数据.如何将我收到的数据提供给浏览器并允许它使用 PDF 响应执行默认操作?

Since I am getting the PDF w/ an ajax call, I'm not sure what to do with the data that I get in the OnSuccess callback. How can I give the data I receive to the browser and allow it to do its default thing with the PDF response?

推荐答案

您根本不需要 jQuery.只需通过表单正常提交您的POST,并在服务器端添加HTTP标头

You don't need jQuery at all. Just submit your POST via a form normally, and on the server side, add the HTTP header

Content-Disposition: attachment; filename="whatever.pdf"

浏览器将执行其默认操作.

The browser will do its default thing.

或者,如果您想在报告 PDF 生成期间可能发生的任何错误时更加小心,您可以这样做.使用 jQuery 将您的参数发布到您的服务器.在服务器上,生成二进制内容并将其缓存在某处几分钟,可通过您放入用户会话的密钥访问,并向您的页面返回一个成功"的 Ajax 响应(或者如果出现错误,则返回一个错误"响应).如果页面返回成功响应,它可以立即执行以下操作:

Alternately, if you want to be more careful about reporting any errors that might occur during the PDF generation, you can do this. POST your parameters to your server with jQuery. On the server, generate the binary content and cache it somewhere for a few minutes, accessible via a key that you put in the user's session, and return a "success" Ajax response to your page (or if there was an error, return an "error" response). If the page gets back a success response, it can immediately do something like:

window.location = "/get/my/pdf";

然后服务器返回缓存的 PDF 内容.确保包含 Content-Disposition 标头,如上所述.

The server then returns the cached PDF content. Be sure to include the Content-Disposition header, as above.

这篇关于POST 到服务器,接收 PDF,使用 jQuery 交付给用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆