您的位置:首页 > 理论基础 > 计算机网络

利用http缓存数据

2016-07-07 20:27 357 查看
通过一个简单的ajax请求来详解http的缓存技术

register.html

<!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

<?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代码如下

<?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">

但不一定有效。。。

缓存技术不一定好,平衡点??
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: