Recursive JavaScript function using array doesn't work
I try to make a recursive function to delete files using jQuery and ajax to show the status of the process. The problem is, the first time the function is executed (index 0) everything is fine and the "output" is "1594.jpg". But when the index is incremented to 1, it's the second caracter of the chain filesToDelete, '5', then '9', and so on.
filesToDelete = new Array();
filesToDelete = '1594.jpg,my.png,test.ogg,Song.mp3,Apple_4S.mov,An App.exe';
filesToDelete = filesToDelete.split(',');
function ajaxDelete(itemList, cpt) {
var tempItemList = itemList;
//If cpt is not initialized, initialize it, make sure it's an integer
if(isNaN(cpt)) cpt = 0*1;
//If cpt is equal to the array, exit
if(cpt >= itemList.开发者_StackOverflowlength) return;
//Current index
var curIndex = cpt;
//The value of the current index
var current = itemList[curIndex];
//DEBUG
console.log('cpt:'+cpt+' index:'+curIndex+' Value:'+itemList[curIndex]);
$.ajax({
url: "deleteFile.php?id="+current,
beforeSend: function(){
progressText('Suppression de '+current);
},
success: function(data){
progressText('Suppression...');
//Index + 1
cpt++;
//RECURTION
setTimeout("ajaxDelete('"+itemList+"', "+cpt+")",1);
}
});
}
Any help is welcomed, with explanation if possible..
Thanks !
Don't rely on the ajax success method for this, if it fails for whatever reason your stuck.
You should do an ajax call per file to delete or better yet send the Array of files to the server and let it take care of it.
for (i = 0; i <= filesToDelete.length; i++)
{
// Ajax Call
$.ajax({
});
}
You're passing in itemList
as a string, but believe it to be an array. (In the setTimeout
call, I mean.)
But I agree with the comment/answer; ew!
Your setTimeout call is executing a string command:
setTimeout("ajaxDelete('"+itemList+"', "+cpt+")",1);
When you concatenate strings and objects, it takes the value of toString() on that object. In the case of an array, that will give you this:
ajaxDelete('1594.jpg,my.png,test.ogg,Song.mp3,Apple_4S.mov,An App.exe', 1)
And strings will accept brackets and give you that character. This will give you '5'
'1594.jpg,my.png,test.ogg,Song.mp3,Apple_4S.mov,An App.exe'[1]
You could omit that parameter and use filesToDelete directly in your call...
精彩评论