停止jQuery .load被caching的响应

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

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

但返回的结果并不总是反映出来。 例如,我改变了堆栈跟踪的响应,但是当我点击searchbutton时堆栈跟踪没有出现。 我查看了控制ajax响应的底层PHP代码,它有正确的代码,并直接访问页面显示正确的结果,但.load返回的输出是旧的。

如果我closures浏览器并重新打开它,它会工作一次,然后开始返回陈旧的信息。 我可以通过jQuery控制这个,或者我需要让我的PHP脚本输出头来控制caching?

如果您想要基于每个请求控制caching,则必须使用更复杂的函数(如$.ajax() 。 或者,如果您只想closures所有内容,请将其放在脚本的顶部:

 $.ajaxSetup ({ // Disable caching of AJAX responses cache: false }); 

这里是一个如何在每个请求的基础上控制caching的例子

 $.ajax({ url: "/YourController", cache: false, dataType: "html", success: function(data) { $("#content").html(data); } }); 

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

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

你在哪里写uniqueId()来每次调用都返回不同的东西。

另一种方法只在需要从服务器获取数据时才将下面的行放在下面,将下面的行跟随您的ajax url。

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

 /** * 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; } 

这在IE中尤其烦人。 基本上你必须把你的响应从服务器发送回去。

萨沙是个好主意,我使用混合。

我创build一个函数

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

并调用我的页面diferents部分例如在init:

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

var ExampleJS = {

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

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

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

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

或者,向查询string添加一个唯一的variables:

 "/portal/?f=searchBilling&x=" + (new Date()).getTime() 

不要使用时间戳来制作一个唯一的URL,因为您访问的每个页面都被jquery mobilecaching在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是否是您要caching的URL,并相应地设置caching参数。

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

你可以用caching设置为false的版本replacejquery的load函数。

 (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加载后运行,你应该全部设置。 您现有的加载代码将不再被caching。

尝试这个:

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

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

我注意到,如果某些服务器(如Apache2)未configuration为明确允许或拒绝任何“caching”,则服务器可能会默认发送“caching”响应,即使您将HTTP标头设置为“no-cache”。 所以确保你的服务器在发送响应之前不“caching”任何内容:

在Apache2的情况下,你必须

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

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

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

这应该做的伎俩禁用服务器端的caching。 干杯! 🙂

此代码可能会帮助你

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

如果你想坚持使用Jquery的.load()方法,像JavaScript时间戳一样添加一些唯一的URL。 “+ new Date()。getTime()”。 注意我不得不添加一个“&time =”,所以它不会改变你的PIDvariables。

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