最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Post complex data using ajax and open returned PDF in new window - Stack Overflow

programmeradmin0浏览0评论

I need to use JQuery ajax to post a plex 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.

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 pletely.

I need to use JQuery ajax to post a plex 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.

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 pletely.

Share Improve this question edited Feb 5, 2018 at 0:18 Groppe asked Dec 30, 2016 at 4:29 GroppeGroppe 3,87913 gold badges46 silver badges68 bronze badges 1
  • See also How to build PDF file from binary string returned from a web-service using javascript, jquery-ajax-blob-arraybuffer.js – guest271314 Commented Dec 30, 2016 at 5:43
Add a ment  | 

1 Answer 1

Reset to default 5

Solution

  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 plete successfully, convert the response to a Blob.
  4. Create an object url to the Blob and open it in a new window.

Notes

  • 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

Code

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);
            }
        }
    };
};

发布评论

评论列表(0)

  1. 暂无评论