我認爲我可以在發送這樣的XMLHttpRequest,發送和安全限制
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.
它應該這樣工作嗎? (我正在使用谷歌瀏覽器。)
有什麼方法可以發現有錯誤嗎? (不看在控制檯中。;-))
UPDATE @giuscri添加的問題非常好,如果我認爲這是異步。我其實錯過了,但事實並非如此。有點令人驚訝。 ;-)
請參閱this example。它包含以下代碼:
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://
此頁面(如上面的鏈接)使用onerror功能無法運行。如果您從file://
運行相同的示例,則運行onerror。
您確定您瞭解異步編程模式嗎? 'xhr.addEventListener(「error」,function(){console.log(「請求失敗。」);})'。見[這裏](http://www.w3.org/TR/XMLHttpRequest/#event-xhr-error)和[這裏](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) – giuscri
好問題,@ giuscri。我更新了我的問題。它不像你期望的那樣工作。 – Leo
'onload'是否用'0'的xhr.status激活?這通常發生在跨源請求上。 – Bergi