如何使用JavaScript检查资源的可用性? [英] How to check the availability of a resource using JavaScript?
问题描述
如果我有一个视频文件的URL,如何检测URL指向的资源是否有效并且在显示之前是否存在?我已经看到一些建议AJAX的答案,但我只知道AJAX发送和检索一些数据,而不是获取文件的状态是否存在。
If I have a URL to a video file, how can I detect if the resource pointed by the URL is valid and exists before it can be displayed? I've seen some answers suggesting AJAX, but I only know AJAX to send and retrieve some data, not to get the status of the file whether it exists or not.
例如,如果我有一个像 http://www.example.com/video.mp4
这样的网址,我怎么能检查 video.mp4
是否存在且可以检索还是不能检索?
For example, if I have a URL like http://www.example.com/video.mp4
, how could I check whether video.mp4
exists or not and can or cannot be retrieved?
推荐答案
你真的不需要ajax,只需创建一个视频元素,看看它是否可以加载源
You don't really need ajax, just create a video element, and see if it can load the source
var video = document.createElement('video');
video.onload = function() {
alert('success, it exsist');
// show video element
}
video.onerror = function() {
alert('error, couldn\'t load');
// don't show video element
}
video.src = 'http://www.example.com/video.mp4';
不同的浏览器播放不同的格式,检查文件是否可以在当前浏览器中播放,你可以使用 canplaythrough
事件
Different browsers play different formats, to check if the file can be played in the current browser, you can use the canplaythrough
event
video.oncanplaythrough = function() {
alert("This file can be played in the current browser");
};
如果文件在同一个域上,并且端口和协议匹配,你可以使用ajax来做一个HEAD请求,看看资源是否存在,但是跨域不起作用
if the file is on the same domain, and ports and protocol match, you can use ajax to do a HEAD request and see if the resource exists, but that won't work cross-domain
var http = new XMLHttpRequest();
http.open('HEAD', '/folder/video.mp4');
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
if (this.status != 404) {
// resource exists
}
}
};
http.send();
这篇关于如何使用JavaScript检查资源的可用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!