2016-12-07 149 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做一个同步请求。

相关问题