What I am trying to do is invoke an HTTPHandler via the $.get method of jQuery which will stream back a PDF and display it in a web page using an object element. My previous method of setting the src attribute of an IFrame to be the result of a handler invocation works, but I would like cross-browser completion notification, so have moved to using $.get(). Sample code:
function buttonClick() {
$.get("/PDFHandler.ashx", {},
function(data, textStatus, XMLHttpRequest) {
var pdfObjectString = "<object data='' type='application/pdf' width='600' height='600'></object>";
var pdfObject = $(pdfObjectString);
pdfObject.attr("data", data);
$("#container").append(pdfObject);
});
As you can see, I am attempting to stick the 'data' variable into an object element. This is not working (no error, PDF just doesn't display), presumably because 开发者_如何学Cthe data that comes back is binary, yet the attr() method expects a string (I think).
My question is thus: how can I invoke an HTTPHandler via $.get and somehow assign the data from the callback to the data attribute of an object?
Based on this question: How to open a file using JavaScript? I was able to work out a solution. Essentially you call the handler again in the success callback function. I couldn't get it working with an <object>
tag (still using an IFrame) but it is good enough for what I need.
For this to work the HTTP handler must be caching the results, otherwise it just gets invoked again.
I have struggled for hours to have something like this work, and this has been my very simple solution that works perfectly:
- On the browser side, I have an iFrame contained in a DIV tag, but can be anywhere you want. You can change iFrame attributes to hide / show it on need basis.
<div id = "divpayframe">
<iframe name="payframe" id="payframe" width="600" height="800" frameborder="0"></iframe>
</div>
- I also have a form that uses the normal submit to the server, but specifies the target as iFrame.
<form id="frmpayslip" method="post" action="/payslip" target="payframe">
The server returns a pdf stream and sets the response content type to application/pdf. See below code (Written in Delphi)
Var S: TMemoryStream;
//Some code generate the pdf file on the server side and convert it to a pdf file stream //Assign the stream to the variable S and set the Response to return the stream
Response.ContentType := 'application/pdf'; Response.SendStream(S);
Note, no custom headers required for this unless you want to send it as attachment instead, in which case you can send 'Content-Disposition','attachment; filename="payslip.pdf"' to achieve the same result.
精彩评论