Home >Web Front-end >JS Tutorial >How to Check for File Existence Using jQuery and JavaScript?
Determining if a server file exists is crucial for various web applications. Here's how to tackle this task using jQuery and pure JavaScript:
jQuery makes it easy to check file existence:
$.ajax({ url: 'http://www.example.com/somefile.ext', type: 'HEAD', error: function() { // File does not exist }, success: function() { // File exists } });
For pure JavaScript, XMLHttpRequest offers an alternative:
function UrlExists(url) { var http = new XMLHttpRequest(); http.open('HEAD', url, false); http.send(); return http.status != 404; }
This method checks for 404 status (file not found).
Note: Asynchronous XMLHttpRequest is deprecated. To implement it asynchronously, consider the following:
function executeIfFileExist(src, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState === this.DONE) { callback(); } }; xhr.open('HEAD', src); xhr.send(); }
The above is the detailed content of How to Check for File Existence Using jQuery and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!