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

今天做项目时候遇到一个问题,由于采用了生成静态的CMS系统,但是页面头部需要显示用户登录的信息,也就是,没有登录时,显示登录框,用户登录后,则显示登录信息。于是用到了js调用php文件的方法。但是由于浏览器的缓存,用户登录后常常还是显示登录框,因为js文件被缓存,没有重新下载。

由于js文件是用<script>标签引入的,无法加随机数参数以使每次都重新下载。经过研究采用以下方法达到目的:

这里是头部的html代码:

<tablewidth="770"border="0"align="center"cellpadding="0"cellspacing="0">
<tr>
<tdwidth="377"height="35"align="left"nowrap="nowrap"id="user_status_div">
<scripttype="text/javascript">...
varjsFile=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>
<tdwidth="393"align="right"nowrap="nowrap"><ahref="http://www.nmc.gov.cn/weatherdetail/57494.html"title="点击查看详细天气预报"target="_blank">武汉</a><spanstyle="font-size:9pt">
<scriptsrc="/weather.php"></script>
</span><span>&nbsp;<ahref="http://www.nmc.gov.cn/weatherdetail/57494.html"title="点击查看详细天气预报"target="_blank">更多</a>&nbsp;&nbsp;<a
onclick="this.style.behavior='url(#default#homepage)';this.sethomepage('http://www.cnmamia.com');returnfalse;"
href
="http://www.qg.org.cn#">设为首页</a>&nbsp;<ahref='#'onClick="javascript:window.external.AddFavorite('{dede:globalname="cfg_basehost"/}','{dede:globalname="cfg_webname"/}');">收藏本站</a></span></td>
</tr>
</table>

这里是生成调用js的php文件:

<?php
if(!isset($_COOKIE['DedeUserID'])||$_COOKIE['DedeUserID']=='')
{
?>
document
.getElementById("user_status_div").innerHTML='<formid="form1"name="form1"method="post"action="/member/index_do.php">[<ahref="/member/index_do.php?fmdo=user&dopost=regnew">会员注册</a>]&nbsp;用户名<inputtype="text"name="userid"id="userid"class="user"/>&nbsp;密码<inputname="pwd"type="password"class="user"/>&nbsp;<inputtype="submit"name="btnsubmit"id="btnsubmit"value="登录"class="login"/><inputtype="hidden"name="fmdo"value="login"><inputtype="hidden"name="dopost"value="login"><inputtype="hidden"name="gourl"id="gourl"value="'+window.location.href+'"><inputname="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=newDedeSql(false);
$query="SelectuseridFrom#@__memberwhereid=".$_COOKIE['DedeUserID'];
$username=$dsql->GetOne($query);
$dsql->Close();
?>
document
.getElementById("user_status_div").innerHTML='欢迎您<?phpecho($username['userid']);?>[<ahref="/member/index.php">用户中心</a>][<ahref="/member/index.php?uid=<?phpecho($username['userid']);?>">我的空间</a>][<ahref="/member/index_do.php?fmdo=login&dopost=exit&forward='+window.location.href+'">退出登录</a>]';
<?php
}
?>

注意这里采用了crateElement方法来动态创建<script>标签,达到了添加随机参数的目的。另外,在调用的js文件中,必须采用innerHTML方法,而不是直接document.write,否则排版可能会不正确。

希望此雕虫小技能给你带来帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值