lundi 22 janvier 2018

Why is this Javascript/Ajax function using a random number?

I'm helping maintain a Javascript-based web site that was written by someone else. In their Javascript code, I came across this function, which downloads a file from the specified URL and calls a callback when the download is complete:

// ajax wrapper
function getServerData(command, command_label, success_callback)
{
   $.ajax({
     url: command,
     type: 'POST',
     data: { rand: (Math.floor(Math.random()*1000)) },
     success: function(data) { success_callback(data); },
     error: function(error) {if (handleError(error, command_label)) {getServerData(command, command_label, success_callback);}}
   });
}

The above makes sense to me, except for this line:

     data: { rand: (Math.floor(Math.random()*1000)) },

Why is there a random number assigned to the data attribute? Is this some attempt to defeat a cacheing mechanism, that will fail to work about 0.1% of the time? Or is it a copy-and-paste-from-an-example detail that wasn't removed even though it's no longer relevant? Or has it some other (even more obscure) purpose?

Simply removing that line doesn't seem to hurt anything, but I'm worried about removing code whose purpose I don't understand.




Aucun commentaire:

Enregistrer un commentaire