如何检查文件是否存在于 jQuery 或纯 JavaScript 中? [英] How do I check if file exists in jQuery or pure JavaScript?

查看:30
本文介绍了如何检查文件是否存在于 jQuery 或纯 JavaScript 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查服务器上的文件是否存在于 jQuery 或纯 JavaScript 中?

How do I check if a file on my server exists in jQuery or pure JavaScript?

推荐答案

使用 jQuery:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

这里是检查404状态的代码,不使用jQuery

Here is the code for checking 404 status, without using jQuery

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

小的变化,它可以检查状态 HTTP 状态代码 200(成功).

Small changes and it could check for status HTTP status code 200 (success), instead.

编辑 2:由于不推荐使用同步 XMLHttpRequest,您可以添加这样的实用方法来异步执行:

EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:

function executeIfFileExist(src, callback) {
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function() {
        if (this.readyState === this.DONE) {
            callback()
        }
    }
    xhr.open('HEAD', src)
}

这篇关于如何检查文件是否存在于 jQuery 或纯 JavaScript 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆