How to check the existence of a server side file on my website server without actually editing it with javascript only. -
this question has answer here:
i have found many questions on topic including stackoverflow. none of them working me. have compiled following existing answers:
function doesfileexist(urltofile) { var xhr = new xmlhttprequest(); xhr.open('head', urltofile, false); // => error message on line xhr.send(); if (xhr.status == "404") { return false; }else { return true; } }
then use function call web server follows:
var thesource = "myurl"; var result = doesfileexist(thesource); if (result == true) { // yes, file exists! console.log('file exists:', thesource); } else { // file not exist! console.log('file not exist:', thesource); }
the error message this:
synchronous xmlhttprequest on main thread deprecated because of detrimental effects end user's experience. more help, check https://xhr.spec.whatwg.org/.
the documentation here should enough started on asynchronous requests.
if explanation not sufficient, try following tutorial writing simple async functions.
http://cwbuecheler.com/web/tutorials/2013/javascript-callbacks/
here's example might help.
how can take advantage of callback functions asynchronous xmlhttprequest?
you use variation of function presented in last link, this. (edited since original posting)
function getrequeststatus(url, callback) { var request = new xmlhttprequest(); request.onreadystatechange = function() { if (request.readystate == 4) { callback(request.status); } }; request.open('get', url); request.send(); } getrequeststatus("http://httpbin.org/status/404", function(status){ if(status == 404){ //it's not found here console.log("not found") } });
but need read articles understand how use function.
once have read articles , run through tutorial may understand syntax below little better. if don't take time understand going on here, struggling next steps how use callbacks in loops etc.
Comments
Post a Comment