繁体   English   中英

使用javascript检查文件是否存在失败

[英]Check if file exists using javascript fails

我在这里有一些答案,但不知何故结果显示我错了。 它所有输出the file exists! 即使它实际上并不存在。

    function doesFileExist(urlToFile) {
      var xhr = new XMLHttpRequest()
      xhr.open('HEAD', urlToFile, false)
      xhr.send()

      return console.log(xhr.status == 200 ? 'File exists' : 'File does not exist')
    }

它输出:

文件已存在

这是服务器文件夹结构:

文件夹结构

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();
    if (xhr.readyState == 4 && xhr.status == 404 ) {
        console.log("File doesn't exist");
        return false;
    } else {
        console.log("File exists");
        return true;
    }
}

doesFileExist('/Framework/views/login/activate_studeasdfnt.php')

试试那个。 我已经测试过了。 抱歉耽误了太长时间。 此外,如果您的功能是测试文件是否存在,我建议您检查 200 响应。 但这取决于你。

尝试检查它是否大于 400

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();
    if (xhr.status >=400 ) {
        console.log("File doesn't exist");
        return false;
    } else {
        console.log("File exists");
        return true;
    }
}

doesFileExist('/Framework/views/login/activate_studeasdfnt.php')
$('#activate_user_level').on('change', function(){
    var user_level = $(this).val(),
        content = $('#content'),
        url = '/views/login/activate_'+ user_level +'.php';

    $.ajax({
        url : controllers('ActivatesController'),
        method : 'POST',
        data : {change_modal_content_activate : 1, url : url},
        success : function(e){
            console.log(e)
        }
    })
})

服务器

if(isset($_POST['change_modal_content_activate'])){
    $url = dirname(__DIR__) . $init->post('url');
    var_dump(file_exists($url));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM