[英]XMLHttpRequest() sometimes works and others not
我有一个函数来执行 XMLHttpRequest() 并且在 Chrome 和 IE 中随机工作。 该功能由 On-click 触发。 试图捕捉错误,我唯一能得到的是 readystate = 4 但由于浏览器拒绝,status = 0。 我会感谢一些帮助。 如果我在 req.send 之后包含最后一个 alert() ,那么只在 IE 中工作得更好。 这是我的功能:
<script type="text/javascript">
function getPDF(Inv, agent, ddId, meth, url){
var invoice = Invoiceid + ".pdf";
console.log("Start");
var req = new XMLHttpRequest();
console.log("opened");
if ("withCredentials" in req) {
// req for Chrome/Firefox/Opera/Safari.
req.open(meth, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
req = new XDomainRequest();
req.open(meth, url);
} else {
// CORS not supported.
req = null;
}
req.setRequestHeader("Content-type", "application/json");
req.setRequestHeader("AGENT", agent);
req.responseType = "blob";
req.onload = function (event) {
var data = event.target.response;
console.log(req.response);
var blob = new Blob([data]);
if (window.navigator.msSaveOrOpenBlob) // IF IE or Edge
window.navigator.msSaveOrOpenBlob(blob,invoice);
else // All Other Browsers
{
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob, {type: "application/pdf"});
a.download = invoice ;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
};
req.onreadystatechange = function (event) {
if (req.readyState === 4) {
if (req.status === 200) {
alert("Open or Save the downloaded file : " + invoice);
} else {
console.log(req.status);
}
}
};
req.onerror = function (event) {
console.log("** An error occurred during the transaction");
};
req.send(null);
alert(1); //
}
</script>
我很确定问题出在 CORS 标头上。 不幸的是,我只是从客户端开发并在外部对服务器端进行故障排除。 我做了什么来解决这个问题,我只是在我的 http 请求中包含了一个额外的标头。 :setRequestHeader("Access-Control-Allow-Origin", "8")。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.