How does jQuery.post() deal with Content-Disposition: attachment?

两盒软妹~` 提交于 2019-12-20 05:16:06

问题


Going slightly crazy here. I'm making an Ajax call using jQuery.post as follows:

  $.post('php/print.php',{data:dS},function(res){...  },"text");

I'm returning from print.php (as a test):

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=test.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "Testing-2-3!";
echo "</body>";
echo "</html>";

The data is coming through fine according to Firebug, including the headers. But how do I get the browser (Firefox, in this instance) to prompt the user to save an attachment?

Thanks.


回答1:


It's simply not possible. AJAX requests never cause user prompts.

However, you can simply make the request return e.g. JSON or plaintext containing the URL and then use location.href = ...; to redirect to it; this will result in the prompt you are looking for.

If the request always results in a file download, you could also consider using a regular form and not using AJAX at all; if the response triggers a download dialog the previous page will remain in the browser window anyway.




回答2:


Why you do not link straight to print.php

and call php output to the browser using this code

$fp = fopen("php://output", 'w');
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=test.doc");
$fp = fopen("php://output", 'w');
fwrite($fp,"your content here");
fclose($fp);


来源:https://stackoverflow.com/questions/9718102/how-does-jquery-post-deal-with-content-disposition-attachment

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