Welcome

首页 / 脚本样式 / Ajax / AJAX页面参数相同时只返回缓存的内容的解决办法

AJAX页面参数相同时只返回缓存的内容的解决办法2011-02-02AJAX页面参数相同时只返回缓存的内容的解决办法

常利用AJAX写一些页面无刷新的内容获取页面,这种方式很快捷也很方便,但其中有一个问题,就是如果两次提交的参数相同时,返回的内容只返回上次获取的内容,如果我们在第一次修改了参数,第二次再次调用却会发现页面根本没有改变。这样的情况是是为AJAX获取时先检查本机缓存,如果本机缓存已有相同内容,则不访问远端服务器。这样的操作倒是可以提高速度和减少服务器压力。但带来的弊端也是显而易见的。

为了解决这个问题。我们必须在获取页加上一个额外的参数。比较简单的方法是用一个随机数。

例子如下

function idCheck() { //参数调用函数

var f = document.modify_form;

var book_num = f.book_num.value;

if(book_num=="") {

window.alert("图书编号不能为空");

f.book_num.focus();

return false;

}

//加一个随机数//////////////////////////////

var number = Math.random();

number = number * 1000000000;

number = Math.ceil(number);

//////////////////////////////////////////

send_request("get_book.php?book_num="+book_num+"&ranum="+number); // 后面的 “ranum=number”是额外加的

}

这样就可以避免相同参数页面返回同样内容的问题了。

还有一种方法为在被调用的页面中,加入代码,禁止本页面被缓存

htm网页

<metahttp-equiv="pragma"content="no-cache">

<metahttp-equiv="cache-control"content="no-cache,must-revalidate">

<metahttp-equiv="expires"content="wed,26feb199708:21:57gmt">

或者<metahttp-equiv="expires"content="0">

asp网页

response.expires=-1

response.expiresabsolute=now()-1

response.cachecontrol="no-cache"

php网页

header("expires:mon,26jul199705:00:00gmt");

header("cache-control:no-cache,must-revalidate");

header("pragma:no-cache");

jsp网页

response.addHeader("pragma", "no-cache");

response.addHeader("cache-control", "no-cache,must-revalidate");

response.addHeader("expires", "0");