最先网上答案讨论比较多的是这一种:
**通过iframe下载
/** * content 下载的url */ function download2(content) { try{ $(".iframe_down").remove().end(); var urlFile=content; var elemIF = document.createElement("iframe"); elemIF.src = urlFile; elemIF.style.display = "none"; document.body.appendChild(elemIF); } catch(e){ } }
缺点:下载不稳定,偶尔会下载两次,尚未查出原因
/*优化*/
通过尝试,找到了完美的方法:通过表单下载
//页面html元素 <iframe style="display: none" name="if_down"></iframe> <form method="post" action="" id="if_down" target="if_down"></form> /** * content 下载的url * id url中需要传的参数 */ function download2(content, id) { try{ var $eleForm = $("#if_down"); $eleForm.attr("action", content); //url中需要带的参数 var input = $("<input>"); input.attr("type", "hidden"); input.attr("name", "id"); input.attr("value", id);//参数id $eleForm.append(input); $eleForm.submit(); } catch(e){ } }
完美解决第一个中所带来的问题,目前没有发现不兼容的浏览器,缺点是在这种post表单提交方式中,无法直接在url中带参,但是可以通过上述代码中的input方式将参数带入。