zoukankan      html  css  js  c++  java
  • 利用http缓存数据

    通过一个简单的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">

    但不一定有效。。。

    缓存技术不一定好,平衡点??

  • 相关阅读:
    apache安全—用户访问控制
    hdu 3232 Crossing Rivers 过河(数学期望)
    HDU 5418 Victor and World (可重复走的TSP问题,状压dp)
    UVA 11020 Efficient Solutions (BST,Splay树)
    UVA 11922 Permutation Transformer (Splay树)
    HYSBZ 1208 宠物收养所 (Splay树)
    HYSBZ 1503 郁闷的出纳员 (Splay树)
    HDU 5416 CRB and Tree (技巧)
    HDU 5414 CRB and String (字符串,模拟)
    HDU 5410 CRB and His Birthday (01背包,完全背包,混合)
  • 原文地址:https://www.cnblogs.com/pcd12321/p/5651481.html
Copyright © 2011-2022 走看看