Javascript XMLHttpRequest、send和安全限制
我想我可以在发送中发现这样的错误Javascript XMLHttpRequest、send和安全限制,javascript,xmlhttprequest,try-catch,Javascript,Xmlhttprequest,Try Catch,我想我可以在发送中发现这样的错误 try { xhr.send(); } catch(e) { // fix-me: With the // bookmarklet on a https page // you can't even send a HEAD // request due to security // restrictions. Check for // this case here. console.log("xhr
try {
xhr.send();
} catch(e) {
// fix-me: With the
// bookmarklet on a https page
// you can't even send a HEAD
// request due to security
// restrictions. Check for
// this case here.
console.log("xhr.send, e=", e, method, window.location.href, url)
debugger;
}
console.log("I am here now");
但是,在xhr.send之后,我从未在catch块中找到console.log语句
在控制台中,我收到了这样的消息
Mixed Content: The page at 'about:blank' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint 'http://m.org/'.
This request has been blocked; the content must be served over HTTPS.
I am here now.
这样行吗?(我正在使用谷歌浏览器。)
有没有什么办法可以发现有错误?(除了在控制台中查看之外。;-)
更新
“吉斯克里加了一个很好的问题,如果我确实认为这是异步的。我真的错过了它的可能,但事实并非如此。有点奇怪。;-)
请看地图。它包含以下代码:
var url = "http://nowhere.org/";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
console.log("onreadystatechance, readyState=", xhr.readyState);
};
xhr.onprogress = function(event) {
console.log("onprogress, readyState=", xhr.readyState);
console.log("onprogress, event=", event);
};
xhr.onerror = function(event) {
console.log("onerror, readyState=", xhr.readyState);
console.log("onerror, event=", event);
};
var method = "HEAD";
xhr.open(method, url, true);
try {
xhr.send();
} catch(e) {
console.log("xhr.send, e=", e, method, window.location.href, url);
}
console.log("After send");
从
https://
运行此页面时(如上面的链接所示),OneError函数不会运行。如果从文件://
运行相同的示例,则会运行OneError。从HTTPS连接到HTTP URI会降低基础加密提供的安全性。Web浏览器会阻止此类请求,直到用户明确允许,以防止明文连接上的数据泄漏。此外,原点(方案、域、端口)也有变化
我允许你链接的页面混合内容,我在控制台中得到了关于不同来源的错误。看起来代码是有效的
顺便说一下,不推荐使用
XMLHttpRequest
支持同步请求,因为它会在请求完成之前阻止用户交互。您确定了解异步编程模式吗xhr.addEventListener(“错误”,函数(){console.log(“请求失败”);})
。看到了,好问题,@giuscri。我更新了我的问题。它没有像您期望的那样工作。onload
是否使用xhr.status
的0
触发?这是跨源请求通常会发生的情况。感谢您的提示,@Bergi,但它不会触发onload
。fire的唯一事件是readystatechange
(xhr.readyState==1)。感谢@Kagomeko,很高兴知道(尽管我认为我从未同步使用XMLHttpRequest
)。