由于ajax函数的返回类型只有xml,text,json,html等类型,并没有"流"类型,所以通过ajax去请求接口是无法下载文件。
1. 方法1 window.open()
jquery 演示
下载一个zip文件
var $btn=$('#btn1')
// 已知一个下载文件的后端端口:https://xxxxxxx/xxx/xxx
$btn.click(function(){
//方法1:window.open
window.open('https://xxxxxxx/xxx/xxx'
})
复制代码
方法1会让浏览器自动的打开一个新的窗口,然后又会迅速关闭,用户体验非常不好
2. 方法2:通过form提交
创建一个form表单来请求接口
下载一个zip文件
var $btn=$('#btn')
// 已知一个下载文件的后端端口:
ar geturl="https://xxxxxxx/xxx/xxx"
$btn.click(function(){
var $form=$('')
$form.attr('action',geturl)
$(document.body).append($form)
//提交表单,实现下载
$form.submit()
})
复制代码
form表单提交知识点:
示例:
// form表单get提交时,action中带参数传递不了
// 但是,get请求会把form表单中的值全部作为参数传递给后端
// 例如,上面的表单form的method为get,那么提交的url:http://localhost/xxxxx/xxxxxxxt/xxxxx?pram1=param1&pram2=param2&pram3=param3&button1=submit
// 如果用post方法提交,后台就可以收到action中的这个参数
// 例如上面的表单form的method为post,那么提交的url为:http://localhost/mywebapp/getPostServlet/getPost.do?param4=param4 -->
// 表单的get请求中如果想传入params4这个参数,可以将参数写在input中,设置隐藏文本域
复制代码
|