简体   繁体   中英

JS: how to check if file exists in JS or AJAX?

i want to check if a local file exists, if it not exists i want to run an alert('File not exists!'). I tried something like this :

 function isOnline() { var xmlPath = "/test/test/myfile.xml" var request=new XMLHttpRequest(); request.open("GET",xmlPath,false); request.send(); if (request.readyState === 4){ return true; }else{ alert('File Away!'); return false; } } 

But this dont work. i cant use PHP or jquery.

If you try to get a resource from a server means the file should be publicly accessible through an URL.

When you launch that request with the XMLHttpRequest object with request.send() that call is asynchronous so checking immediately the readyState or status it will not assure you the end of the call.

function isOnline() {
    var xmlPath = "/test/test/myfile.xml"
    var request=new XMLHttpRequest(); 

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
              alert("File was found on URL");
       }else if (this.readyState == 4 && this.status == 404 ) {
              alert("File away!");
       }
   };
    request.open("GET",xmlPath,false);
    request.send();
}

You should subscribe to the status change event and check the values of that change. So beyond checking for the readyState==4 to get the change to the end of the transaction you should check also for the status code. For example 200 means everything was ok or 404 means the resource was not found.

Check the specification for that codes here: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

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