2016-12-07 279 views
0

試圖使用純JS方法來檢查我是否有有效的JS圖像URL。我收到一個警告,XMLHttpRequest已棄用。有什麼更好的方法來做到這一點?XMLHttpRequest已棄用。代替使用什麼?

urlExists(url) { 
    const http = new XMLHttpRequest(); 
    http.open('HEAD', url, false); 
    http.send(); 
    if (http.status !== 404) { 
     return true; 
    } 
    return false; 
    } 
+0

什麼環境/瀏覽器你得到的警告? –

+2

閱讀你得到的完整警告 – Dekel

+2

[可選的Javascript同步XMLHttpRequest的替代品(在Safari中超時)](http://stackoverflow.com/questions/10076614/alternatives-for-javascript-synchronous-xmlhttprequest-as-時序出在野生動物園) – Xufox

回答

1

你可能會得到那個的XMLHttpRequest的同步使用已被棄用的消息(因爲對用戶體驗的不良影響;它凍結的頁面,同時等待響應)。我可以向你保證,正確的異步使用該API不會被棄用。

下面是一些示例代碼的正確使用:

var xhr = new XMLHttpRequest() 
 
xhr.onreadystatechange = function() { 
 
    if (this.readyState === this.DONE) { 
 
     console.log(this.status) // do something; the request has completed 
 
    } 
 
} 
 
xhr.open("HEAD", "http://example.com") // replace with URL of your choosing 
 
xhr.send()

1

警告,可能是因爲你tyring做一個同步請求。

相關問題