单击 url 而不是 href 发送 ajax 请求。并检查响应状态是否为 200,这意味着文件在那里并且可以下载。如果该文件不存在,您将收到 404 错误状态。在这种情况下,您可以提醒消息。
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(ajaxRequest.status == 200) {
alert("File Found");
document.getElementById("downloadIframe").src = "abc.csv";
}
else
alert("File Not Found");
}
}
ajaxRequest.open("GET", "abc.csv", true);
ajaxRequest.send(null);
}
</script>
<input type = "button" onclick = "ajaxFunction()" value = "Download"/>
<iframe id = "downloadIframe" src ="" style="display:none;"></iframe>
</body>