您使用的服务器端语言是什么?在我的应用程序中,我可以通过在PHP的响应中设置正确的标题轻松地从AJAX调用下载文件:
设置报头服务器端
header("HTTP/1.1 200 OK");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
// The optional second 'replace' parameter indicates whether the header
// should replace a previous similar header, or add a second header of
// the same type. By default it will replace, but if you pass in FALSE
// as the second argument you can force multiple headers of the same type.
header("Cache-Control: private", false);
header("Content-type: " . $mimeType);
// $strFileName is, of course, the filename of the file being downloaded.
// This won't have to be the same name as the actual file.
header("Content-Disposition: attachment; filename=\"{$strFileName}\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . mb_strlen($strFile));
// $strFile is a binary representation of the file that is being downloaded.
echo $strFile;
这实际上会将浏览器“重定向”到这个下载页面,但正如@ahren已经在他的评论中说的,它不会导航离开当前页面。
这一切都是关于设置正确的头文件,所以我相信您会找到适合您所使用的服务器端语言(如果不是PHP的话)的解决方案。
处理响应客户端
假设您已经知道如何进行AJAX调用,那么在客户端向服务器执行AJAX请求。然后服务器生成一个可以下载该文件的链接,例如你想要指向的“转发”URL。
例如,服务器响应如下:
{
status: 1, // ok
// unique one-time download token, not required of course
message: 'http://yourwebsite.com/getdownload/ska08912dsa'
}
在处理响应时,你在你的主体中注入一个iframe,并将iframe的SRC设置为你刚刚接收到的URL,如下所示(使用jQuery来简化这个例子):
$("body").append("<iframe src='" + data.message +
"' style='display: none;' ></iframe>");
如果您如上所示设置了正确的标题,iframe将强制下载对话框,而不需要将浏览器从当前页面导航出去。
Note
关于你的问题的额外补充;我认为使用AJAX技术请求东西时最好总是返回JSON。收到JSON响应后,就可以在客户端决定如何处理它。也许,例如,稍后您希望用户单击指向URL的下载链接,而不是强制直接下载,在您当前的设置中,您将不得不更新客户端和服务器端来实现这一点。