我正在尝试创建自己的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 :)
我试图尝试...赶上xhr.send();但无济于事,仍然无法捕获异常。
任何想法或指针将不胜感激。
最佳答案
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
if (xhr.status==0) {
alert("denied");
} else {
alert("allowed");
}
}
}