简体   繁体   English

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

[英]Check if file exists using javascript fails

I've some of the answers here but somehow the results show me the wrong one.我在这里有一些答案,但不知何故结果显示我错了。 It all outputs the file exists!它所有输出the file exists! even though it does not really 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')
    }

It outputs:它输出:

File Exists文件已存在

This is the server folder structure:这是服务器文件夹结构:

文件夹结构

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

Try that.试试那个。 I have tested it.我已经测试过了。 Sorry for taking too long.抱歉耽误了太长时间。 Also if your function is to test if file exists i would recommend checking for a 200 response.此外,如果您的功能是测试文件是否存在,我建议您检查 200 响应。 But its up to you.但这取决于你。

try checking if it's greater than 400尝试检查它是否大于 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)
        }
    })
})

server服务器

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