注意:在股票交易网站中,缓存的存在不是好事,要禁用缓存,才能实现请求来的数据是实时更新的
register.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
<!
DOCTYPE
>
<
html
>
<
head
>
<
title
>http缓存</
title
>
<
script
type="text/javascript">
window.onload = function() {
var http_request;
var oBtn = document.getElementById('btn');
oBtn.onclick = function() {
sendRequest();
}
}
function sendRequest(){
var u=document.getElementById("username").value;
if(window.ActiveXObject){
http_request=new ActiveXObject("Microsoft.XMLHTTP");
}else{
http_request=new XMLHttpRequest();
}
if(http_request){
var url="UserCheck.php?username="+u;
http_request.open("GET",url,true);
http_request.onreadystatechange=chuli;
http_request.send();
}
}
function chuli(){
if(http_request.readyState==4){
if(http_request.status==200){
var res=http_request.responseText;
console.log(res);
}
}
}
</
script
>
</
head
>
<
body
>
<
form
action="" method="">
用户名字:<
input
type="text" name="username" id="username"><
input
type="button" id="btn" value="验证用户名">
</
form
>
</
body
>
</
html
>
|
UserCheck.php
1
2
3
4
5
6
7
8
9
10
11
12
|
<?php
$expire
=604800;
header(
'Cache-Control: max-age='
.
$expire
);
//1 month
$username
=
$_REQUEST
[
'username'
];
if
(
$username
==
"pcd"
){
echo
"err"
;
}
else
{
echo
"ok"
;
}
?>
|
php中通过
$expire=604800;
header('Cache-Control: max-age='.$expire);//1 month
将缓存设置为一个月,则当进行相同的数据请求时,返回的只会从缓存中取
由上图可得当进行第二次相同的请求时,数据就会从缓存中取
改变UserCheck.php代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
header(
"Expire: -1"
);
header(
"Cache-Control: no-cache"
);
header(
"Pragma: no-cache"
);
//三个均代表禁用缓存,兼容不同的浏览器
$username
=
$_REQUEST
[
'username'
];
if
(
$username
==
"pcd"
){
echo
"err"
;
}
else
{
echo
"ok"
;
}
?>
|
在header中禁用缓存
由图片可得每一次请求都会从新从后台获取数据。
加载html页面时,浏览器会自动缓存css,img,html等文件,强制刷新才会从新加载,可以使用一下代码禁用缓存
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
但不一定有效。。。
缓存技术不一定好,平衡点??