[英]XMLHttpRequest() sometimes works and others not
I have a function to do XMLHttpRequest() and randomly works in both Chrome and IE.我有一个函数来执行 XMLHttpRequest() 并且在 Chrome 和 IE 中随机工作。 The function is triggered by On-click.
该功能由 On-click 触发。 Trying to catch the error the only that I could get is readystate = 4 but status = 0 due the browser rejection.
试图捕捉错误,我唯一能得到的是 readystate = 4 但由于浏览器拒绝,status = 0。 I'll appreciate some help.
我会感谢一些帮助。 If I includes the last alert() after req.send , then work better just in IE.
如果我在 req.send 之后包含最后一个 alert() ,那么只在 IE 中工作得更好。 This is my function:
这是我的功能:
<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>
I'm pretty sure that the issue was with the CORS headers.我很确定问题出在 CORS 标头上。 Unfortunately, I just was developing from the client side and troubleshooting the server side by outside.
不幸的是,我只是从客户端开发并在外部对服务器端进行故障排除。 What I did to fix this issue, I just included an additional header in my http request.
我做了什么来解决这个问题,我只是在我的 http 请求中包含了一个额外的标头。 :setRequestHeader("Access-Control-Allow-Origin", "8").
:setRequestHeader("Access-Control-Allow-Origin", "8")。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.