使用ajax发布复杂数据并在新窗口中打开返回的PDF [英] Post complex data using ajax and open returned PDF in new window

查看:92
本文介绍了使用ajax发布复杂数据并在新窗口中打开返回的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用JQuery ajax将复杂且敏感的数据对象(嵌套对象,数组和个人身份信息)发布到我的服务器,在那里生成PDF并将其返回给客户端。然后,客户端浏览器应在新窗口中打开PDF。

I need to use JQuery ajax to post a complex and sensitive data object (nested objects, arrays, and Personally Identifiable Information) to my server, where a PDF is generated and returned to the client. The client browser then should open the PDF in a new window.

由于数据的性质,请求既不能也不应该是编码的URL - 它必须包含数据作为JSON正文。

Because of the nature of the data the request neither can nor should be an encoded URL - it must include the data as a JSON body.

关于这个问题的其他问题/答案并没有解决我的问题或者没有完全解决问题。

The other questions/answers on this subject did not solve the problem in my case or do not do so completely.

推荐答案

解决方案


  1. 将正文中的数据作为JSON进行POST。

  2. 设置对 arraybuffer 的响应的预期 Content-Type (在客户端和服务器上) )。

  3. 请求成功完成后,将响应转换为 Blob

  4. 创建 Blob 的对象URL并在新窗口中打开它。

  1. POST with the data in the body as JSON.
  2. Set the expected Content-Type of the response to arraybuffer (on the client and server).
  3. When the request has complete successfully, convert the response to a Blob.
  4. Create an object url to the Blob and open it in a new window.

注释


  • JQuery ajax 不支持 arraybuffer Content-Type 所以基地J.必须使用avaScript xhr (如果您没有任何其他选项)。

  • Internet Explorer具有自己的处理功能和显示 Blob ,因此需要特殊情况。

  • 支持的浏览器不包括IE9

  • JQuery ajax does not support the arraybuffer Content-Type so the base JavaScript xhr must be used (if you don't have any other options).
  • Internet Explorer has its own functionality for handling and displaying Blob's, so a special case is needed.
  • Supported browsers does not include IE9

代码

RequestPdf = function (url, data) {
    var request = new XMLHttpRequest(), file, fileURL;
    request.open("POST", url);
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    request.responseType = "arraybuffer";
    request.send(data);
    request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
            file = new Blob([request.response], { type: 'application/pdf' });
            if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
                window.navigator.msSaveOrOpenBlob(file);
            } else {
                fileURL = URL.createObjectURL(file);
                window.open(fileURL);
            }
        }
    };
};

这篇关于使用ajax发布复杂数据并在新窗口中打开返回的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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