我正在尝试创建我自己的 XMLHttpRequest 框架来了解这些东西在内部是如何工作的。 令我困惑的是我找不到如何捕获“同源”异常。
这背后的想法是,我尝试加载一个 URL,如果我遇到同源异常,我会通过该脚本的本地代理脚本重新请求该 URL。我这样做的原因是因为我需要从开发沙箱访问生产数据,并且我希望它对脚本本身尽可能透明。
我知道这是一种不好的做法,但这是目前最不具侵入性的方式:)
只是为了清除问题 - 我不想绕过同源,我只是想捕获抛出的异常,以便我可以做一些事情。
这是我目前用于我的 xhr 的代码:
var net = function (url, cb, setts){
this.url = url;
this.cb = cb;
var oThis = this;
if (!this.xhr) {
this.xhr = new XMLHttpRequest();
this.xhr.onreadystatechange = function() {
if (oThis.xhr.readyState == 4 && oThis.xhr.status == 200) {
document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
}
else {
// do some other stuff :)
document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
}
}
}
this.xhr.open("GET", url,true);
this.xhr.send();
} // It's WIP so don't be scared about the unused vars or hardcoded values :)
我尝试尝试... catch xhr.send();但无济于事,仍然无法捕获异常。
任何想法或指示将不胜感激。
最佳答案
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
if (xhr.status==0) {
alert("denied");
} else {
alert("allowed");
}
}
}
关于javascript - 在 Javascript 中捕获同源异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4318658/