Reputation: 2198
First of all, I already found this solution here: How do I check if file exists in jQuery or JavaScript?
I also tried to use that snippet, but it ends in an infinite-loop for some reason and the response is always "undefined" (even without the loop).
Update
It seems that a redirect-problem of the CMS in the same webspace is causing the infiniteloop. If I'm reading this right, the script stops where it should, but starts running over and over again.
For some reason, the statusCode-effect isn't triggering as well. The log with "nope" never occurs. In Firebug, at the file which isn't existing, it throws a 303 headercode.
HEAD mySite/papger6/index.png
303 See Other 86ms
(Changing the statusCode from 404 to 303 didn't solve the problem.
Update 2
After deleting the CMS and leaving only this script alone, it still runs infinite without triggering the "false" or "failure"-part.
My code now looks like this:
function lookForFiles(helper, imageArray) {
var base_url = window.location.origin;
var pathArray = window.location.pathname.split( '/' );
var absUrl = base_url+"/"+pathArray[1];
$.ajax({
url: absUrl + '/paper' + helper + '/index.png',
type: 'HEAD',
statusCode: {
404: function () {
console.log('nope');
return imageArray;
}
},
success: function () {
console.log(absUrl + '/paper' + helper + '/index.png');
imageArray[helper - 1] = 'paper' + helper + '/index.png';
helper++;
lookForFiles(helper, imageArray);
}
});
}
I have a folderstructure like this:
root
-> paper1
-> index.png
-> paper2
-> index.png
-> paper3
-> index.png
...
My intention is to build a preview for all papers. So I thought: loop through all available folders and store the complete url in an array. As soon as there is no further folder, stop the loop.
This, however, always ends in an endless-loop.
Without using the loop, I get an undefined
when I try to print imageArray[0].
Since everything has to run local, I can't use a complete url with http://www
Upvotes: 0
Views: 2210
Reputation: 3362
Synchronous approach:
function lookForFiles(helper, imageArray){
$.ajax({
url: '/paper' + helper + '/index.png',
type: 'HEAD',
statusCode: {
404: function () {
console.log('nope');
return imageArray;
}
},
success: function () {
console.log('paper' + helper + '/index.png');
imageArray[helper - 1] = 'paper' + helper + '/index.png';
helper++;
lookForFiles(helper,imageArray);
}
});
}
var helper = 1;
var imageArray = new Array;
var images = lookForFiles(helper,imageArray);
Upvotes: 1