-1

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).

Greg Borbonus
  • 1,384
  • 8
  • 16
  • Are you trying to implement a cache-buster? Setting `cache: false` will do this automatically. – Barmar Mar 25 '16 at 21:24
  • I don't know why the original user who asked the question wanted it, but I would imagine that particular use case would be at the top of the list. – Greg Borbonus Mar 25 '16 at 21:28
  • Duplicate: [How to add a parameter to URL in all ajax calls?](http://stackoverflow.com/questions/12318637/how-to-add-a-parameter-to-url-in-all-ajax-calls) and related [Stop jQuery response from being cached](http://stackoverflow.com/questions/168963/stop-jquery-load-response-from-being-cached) – Yogi Mar 25 '16 at 22:01

2 Answers2

4

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;
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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/

Greg Borbonus
  • 1,384
  • 8
  • 16