使用jQuery和iFrame下载文件

我有以下代码下载.csv文件:

 $.ajax({ url: urlString, contentType: "application/json; charset=utf-8", dataType: "json", cache: false, success: function(data) { if (data) { var iframe = $("").attr({ src: data, style: "visibility:hidden;display:none" }).appendTo(buttonToDownloadFile); } else { alert('Something went wrong'); } } }); 

urlString指向Restful服务,该服务生成.csv文件并返回分配给iFrame的src属性的文件路径。 这适用于任何.csv文件,但我遇到.xml文件的问题。

当我使用相同的代码但将contentType更改为text/xml并使用它来下载.xml文件时,这不起作用。

我可以在这里使用相同的方法来处理.xml文件吗?

更新:

感谢Ben指出了正确的方向。 事实certificate我根本不需要ajax调用。 相反,我可以使用iFrame及其url属性来调用Web服务,它将生成内容,添加标题( Content-Disposition ),然后返回流。

我猜测问题是大多数浏览器会尝试在浏览器中呈现XML,而他们往往没有CSV处理程序,所以他们会自动默认提示用户下载文件。 尝试修改XML文件的标头以强制下载。 像(PHP示例):

 header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition: attachment; filename="some filename"'); 

这应该告诉大多数浏览器不要尝试打开文件,而是让用户下载文件并让操作系统确定如何处理它。

如果您无权控制XML文件本身的标头,则可以尝试使用服务器端脚本进行解决。 使用JS将URL传递给服务器端脚本:

 //build the new URL var my_url = 'http://example.com/load_file_script?url=' + escape(path_to_file); //load it into a hidden iframe var iframe = $("").attr({ src: my_url, style: "visibility:hidden;display:none" }).appendTo(buttonToDownloadFile); 

在服务器端(您的http://example.com/load_file_script脚本),您使用cURL / file_get_contents / wgets / [获取远程文件的其他一些机制]来获取远程文件的内容,添加Content-Disposition: attachment标题,并print原始文件的代码。

您也可以从虚拟锚元素下载它,即使数据是客户端:

 /* * Create an anchor to some inline data... */ var url = 'data:application/octet-stream,Testing%20one%20two%20three'; var anchor = document.createElement('a'); anchor.setAttribute('href', url); anchor.setAttribute('download', 'myNote.txt'); /* * Click the anchor */ // Chrome can do anchor.click(), but let's do something that Firefox can handle too // Create event var ev = document.createEvent("MouseEvents"); ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null); // Fire event anchor.dispatchEvent(ev); 

http://jsfiddle.net/D572L/