简体   繁体   中英

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! 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. But its up to you.

try checking if it's greater than 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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