lqixv 发表于 2013-2-7 21:12:43

静态HTML页面不缓存js文件的方法

    今天做项目时候遇到一个问题,由于采用了生成静态的CMS系统,但是页面头部需要显示用户登录的信息,也就是,没有登录时,显示登录框,用户登录后,则显示登录信息。于是用到了js调用php文件的方法。但是由于浏览器的缓存,用户登录后常常还是显示登录框,因为js文件被缓存,没有重新下载。
     由于js文件是用<script>标签引入的,无法加随机数参数以使每次都重新下载。经过研究采用以下方法达到目的:
这里是头部的html代码:
<table width="770" border="0" align="center" cellpadding="0" cellspacing="0"><tr>    <td width="377" height="35" align="left" nowrap="nowrap" id="user_status_div">    <script type="text/javascript">...    var jsFile = document.createElement("script");    jsFile.setAttribute("type","text/javascript");    jsFile.setAttribute("src","/member/user_status_js.php?random="+Math.random());    document.getElementById('user_status_div').appendChild(jsFile);    </script>    </td>    <td width="393" align="right" nowrap="nowrap"><a href="http://www.nmc.gov.cn/weatherdetail/57494.html" title="点击查看详细天气预报" target="_blank">武汉</a><span style="font-size: 9pt">    <script src="/weather.php"></script>    </span><span> <a href="http://www.nmc.gov.cn/weatherdetail/57494.html" title="点击查看详细天气预报" target="_blank">更多</a>  <ahref="http://www.qg.org.cn#">设为首页</a> <a href='#' cfg_basehost"/}','{dede:global name="cfg_webname"/}');">收藏本站</a></span></td></tr></table> 这里是生成调用js的php文件:
<?phpif(!isset($_COOKIE['DedeUserID'])||$_COOKIE['DedeUserID']==''){ ?>document.getElementById("user_status_div").innerHTML='<form id="form1" name="form1" method="post" action="/member/index_do.php">[<a href="/member/index_do.php?fmdo=user&dopost=regnew">会员注册</a>] 用户名<input type="text" name="userid" id="userid" class="user" /> 密码<input name="pwd" type="password" class="user"/> <input type="submit" name="btnsubmit" id="btnsubmit" value="登录" class="login" /><input type="hidden" name="fmdo" value="login"><input type="hidden" name="dopost" value="login"><input type="hidden" name="gourl" id="gourl" value="'+window.location.href+'"><input name="nochvd" type="hidden" id="nochvd" value="1" /></form>'; <?php}else{require_once(dirname(__FILE__)."/config.php");require_once(dirname(__FILE__)."/../include/config_base.php");$dsql = new DedeSql(false);$query="Select userid From #@__member where id=".$_COOKIE['DedeUserID'];$username = $dsql->GetOne($query);$dsql->Close();?>document.getElementById("user_status_div").innerHTML='欢迎您 <?php echo($username['userid']);?> [<a href="/member/index.php">用户中心</a>] [<a href="/member/index.php?uid=<?php echo($username['userid']);?>">我的空间</a>] [<a href="/member/index_do.php?fmdo=login&dopost=exit&forward='+window.location.href+'">退出登录</a>]';<?php}?> 
注意这里采用了crateElement方法来动态创建<script>标签,达到了添加随机参数的目的。另外,在调用的js文件中,必须采用innerHTML方法,而不是直接document.write,否则排版可能会不正确。
希望此雕虫小技能给你带来帮助。
 
本文出处:http://blog.csdn.net/lonestone/archive/2007/11/17/1889741.aspx
页: [1]
查看完整版本: 静态HTML页面不缓存js文件的方法