jquery post 下载文件
时间: 2023-09-28 11:07:34 浏览: 43
使用jQuery的POST方法下载文件需要进行如下步骤:
1. 创建一个隐藏的iframe元素,将其添加到文档中。
```
var $iframe = $('<iframe>', {
id: 'hiddenDownloader',
name: 'hiddenDownloader',
style: 'display: none'
}).appendTo('body');
```
2. 使用POST方法向服务器发送请求,将文件的URL作为请求的数据。
```
$.post(url, postData, function(response) {
// ...
});
```
3. 在回调函数中将服务器响应的内容写入到隐藏的iframe中,这样就会下载到本地。
```
var doc = $iframe[0].contentWindow.document;
doc.open();
doc.write(response);
doc.close();
```
完整的代码如下:
```
var $iframe = $('<iframe>', {
id: 'hiddenDownloader',
name: 'hiddenDownloader',
style: 'display: none'
}).appendTo('body');
$.post(url, postData, function(response) {
var doc = $iframe[0].contentWindow.document;
doc.open();
doc.write(response);
doc.close();
});
```