gpt4 book ai didi

javascript - 基于 AJAX POST 请求发送的 JSON 创建和下载 PDF

转载 作者:行者123 更新时间:2023-11-30 19:33:08 25 4
gpt4 key购买 nike

我正在尝试使用基于客户端 JSON 的 iText 创建 PDF 文件。 HTML 表单数据不适合我,因为它对 JSON 进行编码并且在某些浏览器中无法正常工作,因此我尝试改用 AJAX。但毕竟我得到了一个空的 PDF 文件。

我尝试使用以下内容:

            that.parsedEstimator = JSON.stringify(json); //target object
$.ajax({
type: "POST",
url: "<SERVLET_PATH>",
contentType: "application/json",
cache: false,
data: that.parsedEstimator,
success: function (data) {
a = document.createElement('a');
var binaryData = [];
binaryData.push(data);
a.href = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
a.download = "Estimation.pdf";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
});

有来自servlet的响应处理

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=Estimation.pdf");

我应该怎么做才能解决这个问题?

非常感谢。

最佳答案

responseType 设置为 blob 就可以了,将 xhrFields: {responseType: "blob"} 添加到您现有的代码中,

          $.ajax({
type: "POST",
url: "<SERVLET_PATH>",
contentType: "application/json",
cache: false,
data: that.parsedEstimator,
xhrFields: {responseType: "blob"},
success: function (data) {
a = document.createElement('a');
var binaryData = [];
binaryData.push(data);
a.href = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
a.download = "Estimation.pdf";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
});

关于javascript - 基于 AJAX POST 请求发送的 JSON 创建和下载 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56223958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com