简体   繁体   中英

How do you automatically append to the url of jquery ajax calls

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM