So, I have a lot of ajax calls on my site, and I want to append all the urls with a random string.
So, How would accomplish this?
(asking and answering so it's available).
So, I have a lot of ajax calls on my site, and I want to append all the urls with a random string.
So, How would accomplish this?
(asking and answering so it's available).
You can use $.ajaxPrefilter
to modify any of the $.ajax
options.
$.ajaxPrefilter(function(options) {
options.url += getRandomString(); // defining getRandomString() left as an exercise for the reader
});
If you just want to prevent caching, use jQuery's built-in cache: false
option:
$.ajaxPrefilter(function(options) {
options.cache = false;
});
You can use this code:
function makeid(count) { //Makes a unique string.
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var text = "";
for (var x = 0; x < count; x++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
(function($) { //Extend the existing jquery ajax call.
var _ajax = $.ajax;
$.extend({
ajax: function(o) {
if(o.url){
split='?';
if(o.url.indexOf('?') > 0) split='&'; //Do we already have a bunch of parameters in the url? if so, use & instead of ?
o.url+=split + 'string=' + makeid(10); //append to the string
}
return _ajax.call(this,o);
}
});
})(jQuery);
Example of it working: https://jsfiddle.net/gregborbonus/0a23qdb8/