247

我有以下代码在 URL 上发出 GET 请求:

$('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val());            
});

但返回的结果并不总是反映。例如,我在响应中进行了更改,吐出堆栈跟踪,但是当我单击搜索按钮时堆栈跟踪没有出现。我查看了控制 ajax 响应的底层 PHP 代码,它具有正确的代码,直接访问页面显示了正确的结果,但 .load 返回的输出是旧的。

如果我关闭浏览器并重新打开它,它会运行一次,然后开始返回过时的信息。我可以通过 jQuery 控制它还是需要我的 PHP 脚本输出标头来控制缓存?

4

14 回答 14

424

您必须使用更复杂的功能,例如$.ajax()如果您想根据每个请求控制缓存。或者,如果您只想将其关闭,请将其放在脚本的顶部:

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
于 2008-10-03T21:26:45.140 回答
113

这是一个如何根据每个请求控制缓存的示例

$.ajax({
    url: "/YourController",
    cache: false,
    dataType: "html",
    success: function(data) {
        $("#content").html(data);
    }
});
于 2010-01-28T22:36:59.593 回答
35

一种方法是在 url 末尾添加一个唯一编号:

$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());

您在哪里编写 uniqueId() 以在每次调用时返回不同的内容。

于 2008-10-03T21:26:09.200 回答
9

另一种仅在需要从服务器获取数据时放置下一行的方法,将下一行与您的 ajax url 一起附加。

'?_='+Math.round(Math.random()*10000)

于 2012-12-19T10:07:48.900 回答
6
/**
 * Use this function as jQuery "load" to disable request caching in IE
 * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
 **/
$.fn.loadWithoutCache = function (){
 var elem = $(this);
 var func = arguments[1];
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data, textStatus, XMLHttpRequest) {
   elem.html(data);
   if(func != undefined){
    func(data, textStatus, XMLHttpRequest);
   }
     }
 });
 return elem;
}
于 2010-06-30T13:07:19.690 回答
6

Sasha 是个好主意,我用的是混合的。

我创建一个函数

LoadWithoutCache: function (url, source) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#" + source).html(data);
            return false;
        }
    });
}

并调用我页面的不同部分,例如在 init 上:

初始化:函数(actionUrl1,actionUrl2,actionUrl3){

var ExampleJS= {

Init: function (actionUrl1, actionUrl2, actionUrl3)           ExampleJS.LoadWithoutCache(actionUrl1, "div1");

ExampleJS.LoadWithoutCache(actionUrl2, "div2"); ExampleJS.LoadWithoutCache(actionUrl3, "div3"); } },

于 2011-07-07T19:45:40.880 回答
4

这在 IE 中尤其令人烦恼。基本上,您必须将“无缓存”HTTP 标头与来自服务器的响应一起发回。

于 2008-10-03T21:26:15.690 回答
3

对于 PHP,将此行添加到提供所需信息的脚本中:

header("cache-control: no-cache");

或者,向查询字符串添加一个唯一变量:

"/portal/?f=searchBilling&x=" + (new Date()).getTime()
于 2008-10-04T01:32:11.840 回答
2

不要使用时间戳来创建唯一的 URL,因为您访问的每个页面都由 jquery mobile 缓存在 DOM 中,您很快就会遇到手机内存不足的问题。

$jqm(document).bind('pagebeforeload', function(event, data) {
    var url = data.url;
    var savePageInDOM = true;

    if (url.toLowerCase().indexOf("vacancies") >= 0) {
        savePageInDOM = false;
    }

    $jqm.mobile.cache =  savePageInDOM;
})

此代码在页面加载之前激活,您可以使用 url.indexOf() 来确定 URL 是否是您要缓存的 URL,并相应地设置缓存参数。

不要使用 window.location = ""; 更改 URL,否则您将导航到该地址并且 pagebeforeload 不会触发。为了解决这个问题,只需使用 window.location.hash = "";

于 2012-07-23T08:37:00.900 回答
2

如果您想坚持使用 Jquery 的 .load() 方法,请在 URL 中添加一些独特的内容,例如 JavaScript 时间戳。“+新日期()。getTime()”。请注意,我必须添加一个“&time=”,这样它就不会改变您的 pid 变量。

$('#searchButton').click(function() {
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime());            
});
于 2014-07-09T13:51:25.297 回答
1

您可以将 jquery load 函数替换为缓存设置为 false 的版本。

(function($) {
  var _load = jQuery.fn.load;
  $.fn.load = function(url, params, callback) {
  if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
  }
    var selector, type, response,
      self = this,
      off = url.indexOf(" ");

    if (off > -1) {
      selector = stripAndCollapse(url.slice(off));
      url = url.slice(0, off);
    }

    // If it's a function
    if (jQuery.isFunction(params)) {

      // We assume that it's the callback
      callback = params;
      params = undefined;

      // Otherwise, build a param string
    } else if (params && typeof params === "object") {
      type = "POST";
    }

    // If we have elements to modify, make the request
    if (self.length > 0) {
      jQuery.ajax({
        url: url,

        // If "type" variable is undefined, then "GET" method will be used.
        // Make value of this field explicit since
        // user can override it through ajaxSetup method
        type: type || "GET",
        dataType: "html",
        cache: false,
        data: params
      }).done(function(responseText) {

        // Save response for use in complete callback
        response = arguments;

        self.html(selector ?

          // If a selector was specified, locate the right elements in a dummy div
          // Exclude scripts to avoid IE 'Permission Denied' errors
          jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :

          // Otherwise use the full result
          responseText);

        // If the request succeeds, this function gets "data", "status", "jqXHR"
        // but they are ignored because response was set above.
        // If it fails, this function gets "jqXHR", "status", "error"
      }).always(callback && function(jqXHR, status) {
        self.each(function() {
          callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
        });
      });
    }

    return this;
  }
})(jQuery);

将它放在全局的某个地方,它将在 jquery 加载后运行,你应该已经准备好了。您现有的加载代码将不再被缓存。

于 2016-11-25T17:31:59.160 回答
0

试试这个:

$("#Search_Result").load("AJAX-Search.aspx?q=" + $("#q").val() + "&rnd=" + String((new Date()).getTime()).replace(/\D/gi, ''));

当我使用它时它工作正常。

于 2009-11-11T06:30:32.287 回答
0

我注意到,如果某些服务器(如 Apache2)未配置为明确允许或拒绝任何“缓存”,那么服务器可能默认发送“缓存”响应,即使您将 HTTP 标头设置为“无缓存”。因此,请确保您的服务器在发送响应之前没有“缓存”任何内容:

在 Apache2 的情况下,您必须

1) 编辑“disk_cache.conf”文件 - 禁用缓存添加“CacheDisable /local_files”指令

2) 加载 mod_cache 模块(在 Ubuntu 上“sudo a2enmod cache”和“sudo a2enmod disk_cache”)

3)重启Apache2(Ubuntu“sudo service apache2 restart”);

这应该可以在服务器端禁用缓存。干杯! :)

于 2011-08-15T04:07:29.300 回答
0

此代码可以帮助您

var sr = $("#Search Result");
sr.load("AJAX-Search.aspx?q=" + $("#q")
.val() + "&rnd=" + String((new Date).getTime())
.replace(/\D/gi, ""));
于 2014-05-29T09:54:30.400 回答