How to: jQuery post to ashx file to force download of result?

让人想犯罪 __ 提交于 2019-12-13 19:06:12

问题


I have an ashx handler which takes the 'html' property from the request, then returns that back to whatever called it. I also have the Content-Disposition set as attachment.

Calling the page directly works as expected, forcing a download with a save as dialog.

What I'm stuck on is this: I need to do this from javascript (jQuery). I'll be posting the content of a div and do some further processing.

Could someone give me some pointers on how this is done?

Many thanks.


回答1:


I would (in fact, do :-) ) have a form with a hidden field, copy the content of the div to the field, and then submit the form to a hidden (display: none) iframe.

Including a hidden iframe on the page:

<iframe name="formTarget" src="blank.html" style="display: none">

(E.g., it's initially blank. I actually literally use a blank.html file which is exactly what it sounds like, instead of (say) about:blank because the latter doesn't works quite correctly in some cases; I don't recall the details.)

Telling the form to submit to the iframe and trigger your ashx file:

<form ... action="your.ashx" target="formTarget" ... >

Copying the content of the div to the field:

$("#fieldId").val($("#divId").html()); // Either .html() or .text(), depending on what you want

Submitting the form:

$("#formId").submit();

(Fill in the various "..."s appropriately.)

In my case, I show an overlay div telling the user what I'm doing and start a timer that watches for the content of the iframe (for error messages) and for a status cookie (see this answer for more about the cookie trick). The overlay gets updated or removed depending on the result.



来源:https://stackoverflow.com/questions/3109470/how-to-jquery-post-to-ashx-file-to-force-download-of-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!