Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

ajax - How to check the availability of a resource using JavaScript?

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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';

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");
};

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...