在Javascript中捕获相同的原点异常? [英] Catching same origin exception in Javascript?
问题描述
我正在尝试创建自己的XMLHttpRequest框架,以了解内部如何工作。
令我感到困惑的是,我找不到如何捕获同源异常。
I'm trying to create my own XMLHttpRequest framework to learn how this things work internally. A thing that puzzles me is that I cannot find how to catch a "Same origin" exception.
这背后的想法是我尝试加载一个URL,如果我得到Same origin异常,我会通过脚本本地的代理脚本重新请求URL。我这样做的原因是因为我需要从开发沙箱访问生产数据,我希望它对脚本本身尽可能透明。
The idea behind this is that I try to load a URL, if I get a Same origin exception, I re-request the URL through a proxy script local for the script. The reason I do this is because I need to access production data from a development sandbox and I want it to be as transparent as possible for the script itself.
我知道它是一个不好的做法,但这是目前最不干扰的做法:)
I know it's a bad practice but this is the least intrusive way of doing this at the moment :)
只是为了清除事情 - 我不想绕过相同的来源,我只是我想抓住抛出的异常,这样我就能做些什么。
Just to clear things - I don't want to bypass same origin, I just want to catch the thrown exception so I can do something about it.
这是我目前用于xhr的代码:
Here is the code I currently use for my 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();但是没有用,仍然无法捕捉到异常。
I've tried to try...catch around xhr.send(); but no avail, still can't catch the exceptions.
任何想法或指示都将不胜感激。
Any ideas or pointers would be greatly appreciated.
推荐答案
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
if (xhr.status==0) {
alert("denied");
} else {
alert("allowed");
}
}
}
这篇关于在Javascript中捕获相同的原点异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!