在ajax的应用中,当用户访问一次后,再进行访问当XMLHttpRequest请求不变的时,在ie中会出现这样的现象,那就是取数据不会到服务器端取,而是直接从ie的缓存中取,则会就是ie的缓存问题。在ajax中解决缓存的问题采用时间戳的方式,即为每个XNLHttpRequest请求后面加一个时间戳的标志,从而保证每次请求都是新的从而解决ie缓存问题,下面是简单的例子。
1、关键的代码如下:
//给url地址增加时间戳,骗过浏览器,不读取缓存
function convertURL(url) {
//获取时间戳
var timstamp = (new Date()).valueOf();
//将时间戳信息拼接到url上
//url = "AJAXServer"
if (url.indexOf("?") >= 0) {
url = url + "&t=" + timstamp;
} else {
url = url + "?t=" + timstamp;
}
return url;
}
下面是简单的例子,验证用户点击了验证按钮几次的例子
1、首先看js的代码
function verify() {
//通过jquery方式获取页面文本框中的数值
var url = "AJAXServer?name=" + encodeURI(encodeURI($("#userName").val()));
//通过convertURL对传入的数值做特殊处理,使每个数据都带有一个时间戳,从而产生不同的XHTTPRequest请求
url = convertURL(url);
//调用jquery中的get请求方法向服务器端传值,定义一个回调函数在页面显示服务器端返回的数据
$.get(url,null,function(data){
$("#result").html(data);
});
}
//给url地址增加时间戳,骗过浏览器,不读取缓存
function convertURL(url) {
//获取时间戳
var timstamp = (new Date()).valueOf();
//将时间戳信息拼接到url上
//url = "AJAXServer"
if (url.indexOf("?") >= 0) {
url = url + "&t=" + timstamp;
} else {
url = url + "?t=" + timstamp;
}
return url;
}
2、简单的html验证页面代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>用户名校验ajax实例</title>
<!--<meta http-equiv="content-type" content="text/html; charset=gb2312" />-->
<script type="text/javascript" src="jslib/jquery.js"></script>
<script type="text/javascript" src="jslib/verify.js"></script>
</head>
<body>
<!--ajax方式下不需要使用表单来进行数据提交,因此不用写表单标签-->
<!--ajax方式不需要name属性,需要一个id的属性-->
<input type="text" id="userName" />
<input type="button" value="校验" οnclick="verify()"/>
<!--这个div用于存放服务器段返回的信息,开始为空-->
<!--id属性定义是为了利用dom的方式找到某一个节点,进行操作-->
<div id="result"></div>
</body>
</html>3、服务器端得javaservlet代码
public class AJAXServer extends HttpServlet{
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
try{
httpServletResponse.setContentType("text/html;charset=utf-8");
PrintWriter out = httpServletResponse.getWriter();
Integer inte = (Integer) httpServletRequest.getSession().getAttribute("total");
int temp = 0;
if (inte == null) {
temp = 1;
} else {
temp = inte.intValue() + 1;
}
httpServletRequest.getSession().setAttribute("total",temp);
//1.取参数
String old = httpServletRequest.getParameter("name");
String name = URLDecoder.decode(old,"UTF-8");
//2.检查参数是否有问题
if(old == null || old.length() == 0){
out.println("用户名不能为空");
} else{
//3.校验操作
// String name = old;
if(name.equals("wangxingkui")){
//4。和传统应用不同之处。这一步需要将用户感兴趣的数据返回给页面段,而不是将一个新的页面发送给用户
//写法没有变化,本质发生了改变
out.println("用户名[" + name + "]已经存在,请使用其他用户名, " + temp);
} else{
out.println("用户名[" + name + "]尚未存在,可以使用该用户名注册, " + temp);
}
}
} catch(Exception e){
e.printStackTrace();
}
}
}