Home > Web Front-end > JS Tutorial > How to Check for File Existence Using jQuery and JavaScript?

How to Check for File Existence Using jQuery and JavaScript?

Barbara Streisand
Release: 2024-12-06 10:58:11
Original
487 people have browsed it

How to Check for File Existence Using jQuery and JavaScript?

Detecting 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 Approach

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
    }
});
Copy after login

Pure JavaScript Approach

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;
}
Copy after login

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template