Adding a random number after the URL

前端 未结 5 2078
挽巷
挽巷 2021-01-07 02:43

I\'ve got a site which uses jQuery and Ajax to change the site content without reloading the page. The site contains content which I often change. But somehow the page gets

相关标签:
5条回答
  • 2021-01-07 03:21

    Like most mentionned, you should use the jQuery cache parameter, but for your information, it is often done not using Math.random but with new Date().valueOf(), which is a time value pretty much guaranteed to be unique.

    0 讨论(0)
  • 2021-01-07 03:31
    window.location.hash = $(this).attr('href')
                                .substr(0,$(this).attr('href').length-5)
                                + Math.random();
    
    0 讨论(0)
  • 2021-01-07 03:38

    If you are using jQuery's AJAX functions, try setting $.ajaxSetup( { cache: false } ) at the top of your page, and let jQuery take care of it for you.

    0 讨论(0)
  • 2021-01-07 03:42

    Just use cache : false. jQuery will automatically add a timestamp to the end of the URL for you, making sure that ajax requests are never cached.

    Quoting the the API reference for .ajax()

    cache Default: true, false for dataType 'script' and 'jsonp'

    If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.

    Examples

    1. Globally disable caching for all future ajax requests. See .ajaxSetup()

      $.ajaxSetup({
        cache: false
      });
      
    2. Disable caching per request. See .ajax()

      $.ajax({
        url: "test.html",
        cache: false,
        success: function(html){
          $("#results").append(html);
        }
      });
      
    0 讨论(0)
  • 2021-01-07 03:42

    Best option is to use timestamp with the request:

    window.location.hash = $(this).attr('href')
                                .substr(0,$(this).attr('href').length-5)
                                + timestamp;
    
    0 讨论(0)
提交回复
热议问题