2015-04-19 39 views
1

我認爲我可以在發送這樣的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。

+1

您確定您瞭解異步編程模式嗎? '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

+0

好問題,@ giuscri。我更新了我的問題。它不像你期望的那樣工作。 – Leo

+1

'onload'是否用'0'的xhr.status激活?這通常發生在跨源請求上。 – Bergi

回答

2

從HTTPS連接到HTTP URI會降低基礎加密的安全性。 Web瀏覽器阻止這些請求,直到用戶明確允許,以防止數據泄露超過明文連接。此外,原產地(方案,域名,港口)也有所變化。

我允許混合內容爲您鏈接的頁面,並且我得到了有關控制檯中不同原點的錯誤。看起來像代碼的作品。

順便說一下,不支持使用XMLHttpRequest的同步請求,因爲它會阻止用戶交互,直到請求完成。

+0

感謝@Kagomeko,很高興知道(儘管我認爲我從未同步使用過'XMLHttpRequest' ;-))。 – Leo